使用依赖注入容器,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
文件中,将适配器注入映射器:
模块/我的/config/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 类可以接收注入:
模块/My/src/My/Model/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 检索它或将映射器注入服务,然后将服务注入您要使用它的控制器(或其他服务)。