[英]How to get Zend\Db\Adapter instance from within a Model? (ZF2)
我正在創建用於管理數據庫實體的抽象模型-我已經擁有EntityAbstract
, EntitySetAbstract
和ManagerAbstract
模型。 在我的ManagerAbstract模型中,我需要一個Zend/Db/Adapter
實例才能創建Zend\\Db\\TableGateway
。
如何將適配器的主要實例ManagerAbstract
? 在ZF1中,我可以通過Zend_Registry實現這一目標。
如果這不是在ZF2中做事的正確方法,我很想聽聽對這種事情的正確方法。
謝謝!
使用依賴注入容器Zend\\Di
如果您想在一些工作代碼中四處尋找,ZfcUser項目將執行此操作。
另外,基本方法是這樣的(代碼未經測試!):
首先:配置DI以注入數據庫連接信息:
配置/自動加載/ local.config.php:
<?php
return array(
'di' => array(
'instance' => array(
'Zend\Db\Adapter\Adapter' => array(
'parameters' => array(
'driver' => 'Zend\Db\Adapter\Driver\Pdo\Pdo',
),
),
'Zend\Db\Adapter\Driver\Pdo\Pdo' => array(
'parameters' => array(
'connection' => 'Zend\Db\Adapter\Driver\Pdo\Connection',
),
),
'Zend\Db\Adapter\Driver\Pdo\Connection' => array(
'parameters' => array(
'connectionInfo' => array(
'dsn' => "mysql:dbname=mydatabasename;host=localhost",
'username' => 'myusername',
'password' => 'mypassword',
'driver_options' => array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''),
),
),
),
),
),
);
其次,在模塊的module.config.php
文件中,將適配器注入到映射器中:
模塊/我的/配置/ module.config.php:
<?php
return array(
'di' => array(
// some config info...
'My\Model\ManagerAbstract' => array(
'parameters' => array(
'adapter' => 'Zend\Db\Adapter\Adapter',
),
),
// more config info...
)
);
最后,確保您的ManagerAbstract類可以接收注入:
模塊/我的/ src目錄/我的/型號/ ManagerAbstract.php:
<?php
namespace My\Model;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Adapter\AdapterAwareInterface;
abstract class ManagerAbstract implements AdapterAwareInterface
{
/**
* @var Zend\Db\Adapter\Adapter
*/
protected $adapter;
// some code
public function setDbAdapter(Adapter $adapter)
{
$this->adapter = $adapter;
}
// some more code
}
請注意,要使用任何子類,您需要通過DIC檢索它,或將映射器注入服務中,然后將服務注入要使用它的控制器(或其他服務)中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.