문제

I have following setup in my 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;
            },
        ),
     ),

An then, I'm loading static adapter in onBootstrap() of one of Module's Model class:

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

Is there any possibility to set that just once in config autoloader ? Currrently, if I do that, I still need to call setStaticLOader somewhere in the Module code.

UPDATE: as stated below, that's imposible - at least by standard way.

도움이 되었습니까?

해결책

You can not avoid calling it explicitly in onBootstrap.

General rule is for global/static state to be avoided. Explicitly inject db adapter in factories for you TDG objects instead.

If you still insist on using it, suggest to use delegator factory to make it a bit more flexible. See blogpost for more info about delegators.

Add this to your module config:

'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',
        ),
    ),
)

and then delegator factory:

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;
    }
}

and finally in onBootstrap method

// Force creation of service
$e->getApplication()->getServiceManager()->get('globalDbAdapter');
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top