Showing posts with label Service Locator. Show all posts
Showing posts with label Service Locator. Show all posts

Sunday, 13 January 2013

ZF2: Get db adapter without service locator usage

The problem is: I need to get the instance of TableGateway directly, not via service locator. TableGateway object requires configured dbAdapter object passed to gateway constructor.

Next solution can help with this problem:

1. Use GlobalAdaperFeature as static storage for dbAdapter:
use Zend\Db\TableGateway\Feature;


$feature = new Feature\GlobalAdapterFeature();

2. Add bootstrap method to module config:
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 it is possible to get access to already loaded dbAdapter object in TableGateway constructor:
public function __construct()
{
    $this->featureSet = new Feature\FeatureSet();

    $this->featureSet->addFeature(new Feature\GlobalAdapterFeature());

    $this->initialize();
}

So we have dbAdapter injected into gateway constructor. Ofcourse, it's not best practice, but this allows to add some flexibility to your application, and anyway object dbAdapter was instantiated via service locator, but only once for all tableGateways on the stage of module bootstraping.