Zend Framework 2 : Setting Default Db Adapter via Service initializers
I just read very useful tutorial from akrabat site. He explain about Zend\ServiceManager configuration keys. And, the most I like is about service initializer. It can inject to all instance of something, for example, if Model is extends AbstractTableGateway.
For example, you have SampleTable class like the following :
class SampleTable extends AbstractTableGateway
implements \Zend\Db\Adapter\AdapterAwareInterface
{
protected $table = 'sampletable';
public function setDbAdapter(Adapter $adapter)
{
$this->adapter = $adapter;
$this->resultSetPrototype = new HydratingResultSet();
$this->resultSetPrototype->setObjectPrototype(new Sample());
$this->initialize();
}
}
So, you can initialize of instantiation of all class that implement AdapterAwareInterface like SampleTable.
class Module
{
public function getServiceConfig()
{
return array(
'initializers' => array(
function ($instance, $sm) {
if ($instance instanceof \Zend\Db\Adapter\AdapterAwareInterface) {
$instance->setDbAdapter($sm->get('Zend\Db\Adapter\Adapter'));
}
}
),
'factories' => array(
'SampleModule\Model\SampleTable' => function($sm){
$table = new Model\SampleTable();
return $table;
},
),
);
}
}
Easy setup, thanks Akrabat.
Reference :
http://akrabat.com/zend-framework-2/zendservicemanager-configuration-keys/
Nice one. You could even improve the example a little by using the Zend\Db\Adapter\AdapterAwareInterface.
thanks, updated, cmiiw.
As Ocramius said to me one day, initializers can be dangerous especially with hard dependencies like this. Nothing disallow a user to directly instantiate the object… And boom.
In this case, I think moving the dependency to the constructor and using an abstract factory may be a better idea.
I just follow akrabat said ” Another really common use-case is injecting a database adapter and Zend Framework supplies Zend\Db\Adapter\AdapterAwareInterface for this case”. I just updated my post based on Ralf Eggert suggestion to using Zend\Db\Adapter\AdapterAwareInterface. Can you give me an example to use abstract factory for this case ? I think it will helpful to improve this post.
Thank you very much.
Hello!
To get a parameter set in getServiceConfig ()
I use the controller: $ this-> serviceLocator-> get (‘ParameterName’).
My doubt is how do I get to the same parameter form of a class or a class model … is that possible?
You should read Evan dot pro blog post about it : http://blog.evan.pro/introduction-to-the-zend-framework-2-servicemanager
how can I call via a model class for example?
You should read Evan dot pro blog post about it : http://blog.evan.pro/introduction-to-the-zend-framework-2-servicemanager . It will cover all you need
. I personally suggest you to use injection via factories if you need something for service manager.
[…] Mahlik Ikhsan sorgt dafür, dass das DbAdapaterAwareInterface auch so funktioniert, wie man es erwarten […]