ZF2在config loader中设置静态dbAdapter

时间:2014-05-01 13:25:36

标签: zend-framework2 database-connection bootstrapping

我在development.global.php中有以下设置:

'service_manager' => array(
        'factories' => array(
           'Zend\Db\Adapter\Adapter'
                => 'Zend\Db\Adapter\AdapterServiceFactory',
           'dbAdapter' => function($sm) {

                $config = $sm->get('config');
                $config = $config['db'];
                $dbAdapter = new Zend\Db\Adapter\Adapter($config);
                return $dbAdapter;
            },
        ),
     ),

然后,我在Module的Model类之一的onBootstrap()中加载静态适配器:

 $dbAdapter = $e->getApplication()->getServiceManager()->get('dbAdapter');
 \Zend\Db\TableGateway\Feature\GlobalAdapterFeature::setStaticAdapter($dbAdapter);

是否有可能在配置自动加载器中设置一次?当然,如果我这样做,我仍然需要在模块代码中的某处调用setStaticLOader。

更新:如下所述,这是不可能的 - 至少按标准方式。

1 个答案:

答案 0 :(得分:0)

你无法避免在onBootstrap中明确地调用它。

一般规则是避免全局/静态。而是在工厂中为您的TDG对象显式地注入数据​​库适配器。

如果您仍然坚持使用它,建议使用委托工厂使其更灵活。有关委托人的详细信息,请参阅blogpost

将此添加到您的模块配置:

'service_manager' => array(
    'aliases' => array(
        'globalDbAdapter' => 'Zend\Db\Adapter\Adapter',
    ),
    'delegators' => array(
        // Use alias to make it easier to chose which adapter to set as global
        'globalDbAdapter' => array(
            'YourModule\Factory\GlobalDbAdapterDelegator',
        ),
    ),
)

然后委托工厂:

namespace YourModule\Factory;

use Zend\ServiceManager\DelegatorFactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Db\TableGateway\Feature\GlobalAdapterFeature;

class GlobalDbAdapterDelegator implements DelegatorFactoryInterface
{
    public function createDelegatorWithName(
        ServiceLocatorInterface $serviceLocator,
        $name,
        $requestedName,
        $callback
    ) {
        $dbAdapter = $callback();
        GlobalAdapterFeature::setStaticAdapter($dbAdapter);

        return $dbAdapter;
    }
}

最后是onBootstrap方法

// Force creation of service
$e->getApplication()->getServiceManager()->get('globalDbAdapter');