Symfony 2依赖注入实体函数

时间:2011-12-30 04:47:59

标签: dependency-injection symfony doctrine-orm

我在看http://symfony.com/doc/2.0/cookbook/service_container/parentservices.html

newsletter_manager:
    class:     %newsletter_manager.class%
    parent: mail_manager
    calls:
        - [ setFilter, [ @another_filter ] ]

我应该能够将服务注入函数调用(如果我不理解错误)。但是当我尝试自己的项目时,

myapp.userBridge:
    class: ...\NotesBundle\Bridge\UserBridge
    arguments:
        - '@doctrine.orm.entity_manager'
myapp.user:
    class: ...\UserBundle\Entity\User
    calls:
        - [ initUserNotesBundle, [ @myapp.userBridge ] ]
        - [ cleanupUserNotesBundle, [ @myapp.userBridge ] ] 

但是当调用该函数时(Doctrine 2生命周期回调:PrePersist)

public function initUserNotesBundle(UserBridge $userBridge) {
    $userBridge->prePersistUser($this);
}

它给出了

Catchable Fatal Error: Argument 1 passed to ...\UserBundle\Entity\User::initUserNotesBundle()
must be an instance of ...\NotesBundle\Bridge\UserBridge, none given,
called in ...\Doctrine\ORM\Mapping\ClassMetadataInfo.php on line 1540
and defined  in ...\UserBundle\Entity\User.php line 319

1 个答案:

答案 0 :(得分:20)

这不是这个问题的答案,而是解决这个问题的另一种方法。我发现我可以使用Event Listeners

services:
    my.listener:
        class: Acme\SearchBundle\Listener\SearchIndexer
        tags:
            - { name: doctrine.event_listener, event: postSave }

class SearchIndexer
{
    public function postSave(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        $entityManager = $args->getEntityManager();

        // perhaps you only want to act on some "Product" entity
        if ($entity instanceof Product) {
            // do something with the Product
        }
    }
}