1

My goal is to use DI in ancestor objects using setters so I have a common DI for ancestor objects. e.g. an abstract model class my other models inherit from, preconfigured with an entity manager etc.

So far, after configuring the ancestor and creating it with DI successfully, changing it to an abstract class, then instantiating an ancestor of that class the DI for the abstract (whether set to abstract or not) doesn't run.

namespace Stuki;

use Doctrine\ORM\EntityManager;

# abstract
class Model {
    protected $em;

    public function setEm(EntityManager $em) {
        $this->em = $em;
    }
}

The DI for this class

'di' => array(

    'instance' => array(

        'Stuki\Model' => array(
            'parameters' => array(
                'em' => 'doctrine_em'
            )        
        ),

The above class and DI will work. But I want that to run on ancestor objects so

namespace Stuki\Model;

use Stuki\Model as StukiModel;

class Authentication extends StukiModel {
    public function getIdentity() {
        return 'ħ'; #die('get identity');
    }
}

$auth = $e->getTarget()->getLocator()->get('Stuki\Model\Authentication');

The last line, $auth = , doesn't run the DI.

How can I setup DI for ancestor objects, without using introspection?

4

1 回答 1

0

抱歉,当我通过 Meetup 回复时,我的假设不正确;)

您的问题的症结在于您将 Stuki\Model 配置为在 InstanceManager 中使用 EntityManager,但要求 Di 提供 Stuki\Authentication。

您可以切换到构造函数注入...这可行,但我真的不喜欢在祖先类中定义构造函数:

class EntityManager {

}

# abstract
abstract class Model {
    protected $em;

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

class Authentication extends Model {
    public function getIdentity() {
        return 'ħ'; #die('get identity');
    }
}

$di = new Zend\Di\Di();
$im = new Zend\Di\InstanceManager();
$di->setInstanceManager($im);
$auth = $di->get('Authentication');
var_dump($auth);

需要注意的一点是,在我们的两个示例中,Di 仍然需要使用自省来发现实例化器、方法和方法参数等内容。在运行时避免自省的唯一方法是预编译:http ://packages.zendframework.com/docs/latest/manual/en/zend.di.definition.html#zend.di.definition.compilerdefinition 。

于 2012-01-06T23:32:09.803 回答