2012-01-06 103 views
1

我的目标是在使用setter的祖先对象中使用DI,所以我有一个共同的DI用于祖先对象。例如我的其他模型继承的抽象模型类,预配置了实体管理器等。ZF2依赖注入吸热体对象

到目前为止,在配置祖先并使用DI成功创建祖先之后,将其更改为抽象类,然后实例化该类的祖先摘要的DI(无论是否设置为抽象)不会运行。

namespace Stuki;

use Doctrine\ORM\EntityManager; 

# abstract 
class Model { 
    protected $em; 

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

的DI此类

'di' => array(

'instance' => array(

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

上面的类和DI会工作。但我想,要对祖先运行对象,因此

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'); 

最后一行,$ AUTH =,不运行DI。

如何在不使用自省的情况下为祖先对象设置DI?

+0

从一个学说实体的角度来看,实体不应该是entitymanager意识到的。我想你是用SpiffyDoctrineORM来支持zf2原则吗? – Fge 2012-01-06 22:56:06

回答

0

对不起我的假设是不正确的,当我通过聚会回答;)

你的问题的关键是要配置Stuki \模式,以一个EntityManager在InstanceManager,但问迪的Stuki \认证。

您可以切换到构造注射......这个工作,但我真的不喜欢有祖先类定义构造函数:

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); 

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