我试图使用zend表达方式,现在看看如何做数据库的东西。我在看this,但目前尚不清楚。我使用composer来安装zend-db,它提到在dependencies.global.php中添加一行,然后在工厂类中使用容器来获取适配器,但之后没有谈到如何在实际操作中访问它所以我不知道发生了什么,因为适配器对象超出了其他类的范围。
从开始到结束,任何人都有良好而明确的例子,实际上能够连接和查询sql吗?
答案 0 :(得分:1)
尝试通过工厂注入你的db类,按照骨架应用程序的例子,你可以这样做:
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;
}
在您的配置提供程序中,您需要将表配置为工厂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);
},
],