📜 ⬆️ ⬇️

ZF2: Get db adapter without using service locator

Hello readers!

Many developers began to study Zend framework 2 and, most likely, faced the problem of using a permanent adapter for the database. I would like to share with you an interesting article that helped me resolve this issue.


')
The problem is to get the TableGateway instance directly, and not through the service locator.
The TableGateway object requires you to configure the dbAdapter object sent to the designer gateway.

The following solution will help solve this problem:

1. Use GlobalAdaperFeature as static storage for dbAdapter:

use Zend\Db\TableGateway\Feature; $feature = new Feature\GlobalAdapterFeature(); 


2. Add the bootstrap method to the module configuration file:

 public function onBootstrap($e) { // set static adapter for all module table gateways $serviceManager = $e->getApplication()->getServiceManager(); $dbAdapter = $serviceManager->get('Zend\Db\Adapter\Adapter'); Feature\GlobalAdapterFeature::setStaticAdapter($dbAdapter); } 


3. Now you can access the already loaded dbAdapter object in the TableGateway constructor:

 public function __construct() { $this->featureSet = new Feature\FeatureSet(); $this->featureSet->addFeature(new Feature\GlobalAdapterFeature()); $this->initialize(); } 


Thus, we have a dbAdapter embedded in the gateway of the constructor. Of course, this is not the best practice, but it does add some flexibility to your application, but in any case, the dbAdapter object was created using the service locator, but as a singleton method for all tableGateways at the bootstrap module level.

Source: https://habr.com/ru/post/175523/


All Articles