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?
You will need to inject the adapter into your model when it's created, for example using a factory.
for example in your config:
You would then create the factory which will inject the adapter into your model:
You would then obviously need to make your model accept the adapter in it's constructor in this case.
Now where ever you need to get an instance of your model with the adapter injected you'd call:
This will call the factory and bring back the model complete with adapter.
You would then use the same kind of approach to inject your model into any controllers or service classes where it's needed. As said in a previous post try and avoid injecting the service locator/Service manager directly into your objects, but rather use it to add the items you need (adapters/mappers etc) from inside Factory classes etc.