Jiew Meng
Jiew Meng

Reputation: 88197

Symfony 2 Dependency Injection into Entity Function

I am looking at http://symfony.com/doc/2.0/cookbook/service_container/parentservices.html

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

I am supposed to be able to inject services into function calls (if I didn't understand wrongly). But when I tried in my own project,

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

But when the function is called (Doctrine 2 Life Cycle Callback: PrePersist)

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

It gives

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

Upvotes: 9

Views: 6470

Answers (1)

Jiew Meng
Jiew Meng

Reputation: 88197

Not an exactly an answer to this question, but an alternate method of solving this problem. I found I can use 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
        }
    }
}

Upvotes: 20

Related Questions