【问题标题】:ZF2 set static dbAdapter in config loaderZF2 在配置加载器中设置静态 dbAdapter
【发布时间】:2014-05-01 13:25:35
【问题描述】:

我的 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);

有没有可能在 config autoloader 中只设置一次?目前,如果我这样做,我仍然需要在模块代码中的某处调用 setStaticLOader。

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

【问题讨论】:

    标签: zend-framework2 database-connection bootstrapping


    【解决方案1】:

    你无法避免在 onBootstrap 中显式调用它。

    一般规则是避免全局/静态状态。改为在工厂中为您的 TDG 对象显式注入 db 适配器。

    如果你仍然坚持使用它,建议使用委托工厂,使其更灵活一点。有关委托人的更多信息,请参阅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');
    

    【讨论】:

    • 您好,非常感谢您的意见,但是 - 也许我遗漏了一些东西 - 最后您需要在 onBootstrap 中调用服务管理器,不是吗? :)
    • 是的。正如我所说,没有办法解决这个问题。除非您将停止使用全局数据库适配器。这是强烈推荐的方法。
    • 好吧,我想我会回到 ZF1。我希望 ZF2 能让一些事情变得更容易,但不幸的是我陷入了很多手动操作。非常感谢您的努力。
    • 顺便说一句,我接受你的回复,现在很清楚,我不能简单地这样做:)
    猜你喜欢
    • 2013-12-04
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    相关资源
    最近更新 更多