Reputation: 2499
I'm trying to use zend expressive and looking at how to do database stuff now. I was looking at this, but it's not clear. I used composer to install zend-db and it mentioned to add a line in dependencies.global.php and then use container in the factory class to get the adapter but then didn't talk about how to access it in the actual action class so I don't know what's going on as the adapter object is out of scope from other class.
Anyone has good and clear example from start to finish to actually able to connect and query sql?
Upvotes: 3
Views: 1390
Reputation: 279
try to inject your db class via factory, follow example on skeleton app, you can do something like this:
HomePageFactory.php
public function __invoke(ContainerInterface $container)
{
$router = $container->get(RouterInterface::class);
$template = $container->has(TemplateRendererInterface::class) ? $container->get(TemplateRendererInterface::class) : null;
$adapter = $container->get( Adapter::class );
$usersTable = $container->get( Table\UsersTable::class );
return new HomePageAction($router, $template,$adapter,$usersTable);
}
HomePageAction.php
class HomePageAction implements ServerMiddlewareInterface
{
/**
* @var Router\RouterInterface
*/
private $router;
/**
* @var null|Template\TemplateRendererInterface
*/
private $template;
/**
* @var Adapter
*/
private $dbAdapter;
/**
* @var UsersTable
*/
private $usersTable;
/**
* HomePageAction constructor.
* @param Router\RouterInterface $router
* @param Template\TemplateRendererInterface|null $template
* @param Adapter $adapter
* @param UsersTable $usersTable
*/
public function __construct( Router\RouterInterface $router, Template\TemplateRendererInterface $template = null, Adapter $adapter, Table\UsersTable $usersTable )
{
$this->router = $router;
$this->template = $template;
$this->dbAdapter = $adapter;
$this->usersTable = $usersTable;
}
on your config provider where you have your tables u have to config dependencies as factory EX:
'factories' => [
Table\UsersTable::class => function($container) {
$dbAdapter = $container->get( AdapterInterface::class );
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype( new Model\Users() );
$tableGateway = new TableGateway('users', $dbAdapter, null, $resultSetPrototype);
return new Table\UsersTable($tableGateway);
},
],
Upvotes: 1