Zend Framework 2 model database adapter depedency injection
Typically most of the model classes depend on database adapter. First way to get database adapter instance is to request it via service manager every time you need it. Second, and more convenient one, is to let Zend\Di do all the magic for you. To achieve this you need to implement Zend\Db\Adapter\AdapterAwareInterface in your model class. Or write an abstract class that implements this interface and extend it with your model class and Zend\Di will inject database adapter dependency. Note: to make this work you should instantiate model classes via ServiceManager. How to setup a database adapter is explained in Getting Started with Zend Framework 2.
Abstract class example:
Use in you model class like this:
Instantiate model class like this:
Abstract class example:
<?php //module/<YOUR_MODULE>/src/<YOUR_MODULE>/Model/AbstractAdapterAware.php namespace <YOUR_MODULE>\Model; use Zend\Db\Adapter\Adapter; use Zend\Db\Adapter\AdapterAwareInterface; abstract class AbstractAdapterAware implements AdapterAwareInterface { /** * Database instance * * @var \Zend\Db\Adapter\Adapter */ protected $db; /** * Set database adapter * * @param Adapter $db * @return void */ public function setDbAdapter(Adapter $adapter) { $this->db = $adapter; } }
Use in you model class like this:
<?php //module/<YOUR_MODULE>/src/<YOUR_MODULE>/Model/Example.php namespace <YOUR_MODULE>\Model; class Example extends AbstractAdapterAware { public function exampleMethod() { $this->db->query(...); } }
Instantiate model class like this:
<?php namespace <YOUR_MODULE>\Controller; use Zend\Mvc\Controller\AbstractActionController; class SomeController extends AbstractActionController { public function indexAction() { $this->getServiceLocator()->get('<YOUR_MODULE>\Model\Example')->exampleMethod(); } }
Comments
Post a Comment