ZF2 Injection Dependence Aliases and Multiple Instances

We are currently writing a module in Zend Framework 2.

I have some problems finding documentation on this, but I know that this is possible.

I have 3 classes in the hierarchy that I would like to configure through dependency injection. Let me name these classes; ClassA, ClassB and ClassC.

ClassA contains an array of ClassB instances, and ClassB contains an array of ClassC instances. Each instance of ClassB must be created using different parameters. The same goes for ClassC. Parameters for all 3 classes are passed through the constructor (this can also be processed using the setter, if necessary).

<?php
class ClassA {
    protected $arrClassBInstances = array();

    public function __construct( $arrClassBInstances ) {
         $this->arrClassBInstances = $arrClassBInstances;
    }
}

class ClassB {
    protected $arrClassCInstances = array();
    protected $someOtherParam = "";

    public function __construct( $arrClassCInstances, $someOtherParam ) {
         $this->arrClassBInstances = $arrClassCInstances;
         $this->someOtherParam = $someOtherParam;

    }
}

class ClassC {
    protected $someParam = "";

    public function __construct( $someParam ) {
         $this->someParam = $someParam;
    }
}

, . -, ? , ClassB, ClassC. ZF2 DiC - .

-, . , ClassB ClassA?

, DiC DI .config.php.

+3
3

, , :

// $event instance of \Zend\Mvc\MvcEvent
$di = $event->getTarget()->getLocator();
$paramsForA = array(
    $di->get('qualified_namespaces_or_di_alias_for_b', array('arrClassCInstances'=>array(
        $di->get('qualified_namespaces_or_di_alias_for_c', array('someParam'=>1)),
        $di->get('qualified_namespaces_or_di_alias_for_c', array('someParam'=>2)),
    ))),
    $di->get('qualified_namespaces_or_di_alias_for_b', array('arrClassCInstances'=>array(
        $di->get('qualified_namespaces_or_di_alias_for_c', array('someParam'=>3)),
        $di->get('qualified_namespaces_or_di_alias_for_c', array('someParam'=>4)),
    ))),
);
$classA = $di->get('qualified_namespaces_or_di_alias_for_a', array('arrClassBInstances'=>$paramsForA));

DI alias, full qualified namespace $di->get()

0

I just wrote a post on this topic. I personally do not use the Di or DiC class, but I hope you find that the concepts can be directly applied to your question, especially in Part 2, regardless of what you decide to use as your IoCC. http://zendblog.shinymayhem.com/2012/09/using-servicemanager-as-inversion-of.html

0
source

All Articles