Search code examples
phpdatabasezend-framework2zend-db

Zend Framework 2 - How to access DB adapter in controller


Despite several hits on Google I still couldn't find out how to access the db adapter I configured in my global.php in any controller.

I found this:

$db = $this->getParam('bootstrap')->getPluginResource('db')->getDbAdapter();

But it's giving me a ServiceNotFoundException.

Could anybody be so kind to just tell me a quick way to get to the db adapter for making an raw SQL query? (yes, I know that it shouldn't to this but its just temporary)

Thanks!


Solution

  • You'd access these kind of things through the ServiceManager. Try the following:

    $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'); 
    // replace 'Zend\Db\Adapter\Adapter' with name of adapter if different