I am learning ZF2.
Can I use getServiceLocator() to get a adapter in a Model?
/config/autoload/global.php
return array(
'db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=zf2tutorial;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
),
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
),
'aliases' => array(
'db' => 'Zend\Db\Adapter\Adapter',
),
),
);
/config/autoload/local.php
return array(
'db' => array(
'username' => 'YOUR USERNAME HERE',
'password' => 'YOUR PASSWORD HERE',
),
);
So, how can I use:
$sm = $this->getServiceLocator();
$this->dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
to get a adapter in a Model?
If you are using the latest Zend Framework version you cannot use the
getServiceLocatormethod in your controller classes since both theServiceLocatorAwareInterfaceand theServiceManagerAwareInterfacewere removed.So this line:
Won't work as you maybe expected in your controller class.
You can also read more on this change in the migration guide:
You will need to refactor your service and probably the best way to do that is to create a service factory where you inject your dependencies.
Check also this blog post (chapter Factories) on more details on how to build a factory.