zend framework2 - Reducing service config duplication with a custom service locator? -


my app uses data mapper pattern, have number of mapper classes, each needs instance of database adapter. factories section of service config filled entries this:

'usermapper' => function($sm) {     $mapper = new usermapper();     $adapter = $sm->get('zend\db\adapter\adapter');     $mapper->setadapter($adapter);      return $mapper; }, 'groupmapper' => function($sm) {     $mapper = new groupmapper();     $adapter = $sm->get('zend\db\adapter\adapter');     $mapper->setadapter($adapter);      return $mapper; }, 

i remove of boiler plate code. possible me define custom service locator class these mappers, instantiate mapper class suppliyng db adapter, unless definition exists custom factory configuration?

there 2 ways approach this.

the first have mappers implement zend\db\adapter\adapterawareinterface, , add initializer service manager inject adapter services implementing interface. if that, mappers placed in invokables key of service config instead of needing factory each.

your mappers similar this

<?php namespace foo\mapper;  use zend\db\adapter\adapter; use zend\db\adapter\adapterawareinterface; // if you're using php5.4 can make use of trait // use zend\db\adapter\adapterawaretrait;  class barmapper implements adapterawareinterface; {     // use adapterawaretrait;      // ..     /**      * @var adapter      */     protected $adapter = null;      /**      * set db adapter      *      * @param adapter $adapter      * @return mixed      */     public function setdbadapter(adapter $adapter)     {         $this->adapter = $adapter;          return $this;     }  } 

in service manager config, place mappers under invokables, , add initializer adapteraware services

return array(    'invokables' => array(        // ..        'foo/mapper/bar' => 'foo/mapper/barmapper',        // ..     ),     'initializers' => array(         'zend\db\adapter' => function($instance, $sm) {             if ($instance instanceof \zend\db\adapter\adapterawareinterface) {                 $instance->setdbadapter($sm->get('zend\db\adapter\adapter'));             }         },     ), ); 

the alternative method create mapperabstractservicefactory, , answer -> zf2 depency injection in parent describes how might that.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -