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.

6 comments:

  1. Thanks for sharing your info. I really appreciate your efforts and I will be waiting for your further write

    potaup

    ReplyDelete
  2. Your blog posts are more interesting and impressive. I think there are many people like and visit it regularly, including me.I actually appreciate your own position and I will be sure to come back here.
    instagram online photo

    ReplyDelete
  3. Wonderful information! I am looking for these types of blogs for last many days. Keep it up. Thanks for sharing it with us e-commerce web development services and mobile app development company

    ReplyDelete