9

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

1 Answer 1

20

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
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

that's not an alternate method, that's the right method :D Injecting services into entities is bad practice, they're meant to be POPOs
Plain Old PHP Object just as POJO is a Plain Old Java Object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.