In this example, I am going to show to how you can connect your data model to table in database and do the basic database operations like Select, Insert, Update, Delete
I am using Zendframework3 skeleton application, you can see this artille if you are not familiar with how to install it
Where do you put your database setting?
To your config.autoload.global.php
file, you can add the following code to commect to Mysql database in your localhost
"db" => [ 'driver' => 'Pdo_Mysql', 'dsn' => 'mysql:dbname=restapi;host=127.0.0.1', 'username' => 'root', 'password' => '' ];
Now you can create the Product.php
at Module\Application\src\Model and add the following code to it
name = (!empty($data['name'])) ? $data['name'] : null; $this->price = (!empty($data['price'])) ? $data['price'] : null; } }
You create the ProductTable.php at the same location and add the following code to do all database operations
tableGateway = $tableGateway; } public function fetchAll() { $resultSet = $this->tableGateway->select(); return $resultSet; } }
What does TableGateway
does in zendfraework?
TableGateway represents a table in a database. With the TableGateway interface you can do the most common table opretions like select,insert,update,delete
I can use the getServiceConfig()
to load the factories. So you can add the following code to Module.php
file loacted at Module\Application\src\
public function getServiceConfig(){ return [ 'factories'=>[ Model\ProductTable::class => function($container){ $tableGateway = $container->get(Model\ProductTableGateway::class); return new Model\ProductTable($tableGateway); }, Model\ProductTableGateway::class => function ($container) { $dbAdapter = $container->get(AdapterInterface::class); $resultSetPrototype = new ResultSet(); $resultSetPrototype->setArrayObjectPrototype(new Model\Product()); return new TableGateway('products', $dbAdapter, null, $resultSetPrototype); } ] ]; }
Finally you can add another configuration to module.config.php
located at module\Application\config
'controllers' => [ 'factories' => [ Controller\IndexController::class => InvokableFactory::class, Controller\ProductController::class => function($container) { return new Controller\ProductController($container->get(Model\ProductTable::class)); } ], ],