简体   繁体   中英

No database adapter was found in the static registry

For the first time faced with such a problem... When trying to get a static adapter in the zf2:

$this->adapter = \Zend\Db\TableGateway\Feature\GlobalAdapterFeature::getStaticAdapter();

...for example in the constructor of my plugin I receive an error:

No database adapter was found in the static registry.

My global config file looks like:

<?php
//config/global.php

return array(
    'db' => array(
        'driver'            => 'Pdo',
        'dsn'               => 'mysql:dbname=example-db;host=localhost',
        'driver_options'    => array(
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "UTF8"'
        ),
    ),

    'service_manager' => array(
      'factories' => array(
         'Zend\Db\Adapter\Adapter' => function ($serviceManager) {
            $adapterFactory = new Zend\Db\Adapter\AdapterServiceFactory();
               $adapter = $adapterFactory->createService($serviceManager);
               // set static adapter
               \Zend\Db\TableGateway\Feature\GlobalAdapterFeature::setStaticAdapter($adapter);

               return $adapter;
         }
      ),
   ),
);

Who knows what could be the problem? Thanks.

When you register a factory with the service manager you have to request it before it will create the instance. This is a big change from Zend 1 where they had singletons for major components like the db adapter. The advantage of this approach is scalability, which is where Zend 1 stumbled.

You can fetch the adapter anywhere you can access the service locator. For example in the controller you can do something like this:

$sl = $this->getServiceLocator();
$adapter = $sl->get('Zend\Db\Adapter\Adapter');

This problem have been resolved as follows:

    // module/Application/Module.php
    public function onBootstrap(MvcEvent $e)
    {
         $sm = $e->getApplication()->getServiceManager();
         $adapter = $sm->get('Zend\Db\Adapter\Adapter');
\Zend\Db\TableGateway\Feature\GlobalAdapterFeature::setStaticAdapter($adapter);
    }

I think that there's the best way to integrate the static adapter in application which allows get it easily in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM