I wish to use setter injection on my article entity, but I’m new to this and don’t understand it too well.
My error is:
My\NewsBundle\Entity\Article
Fatal error: Call to a member function addArticle() on a non-object
This happens here in my article entity:
/** Inject service: search */
protected $search;
public function setSearch(Search $search)
{
$this->search = $search;
}
/** @ORM\PostPersist */
public function postPersist()
{
// wrong: does not have id yet for prePersist; changed to postPersist
//$search = new \My\NewsBundle\Entity\Search();
echo get_class($this->search);
$this->search->addArticle($this);
}
FYI: my config.yml has:
# Parameters
parameters:
search.class: My\NewsBundle\Entity\Search
google.class: My\NewsBundle\Entity\Google
flickr.class: My\NewsBundle\Entity\Flickr
article.class: My\NewsBundle\Entity\Article
# Servers
services:
search:
class: %search.class%
google:
class: %google.class%
flickr:
class: %flickr.class%
article:
class: %article.class%
calls:
- [setSearch, [@search]]
FYI: I’m running a ContainerAwareCommand and that consumes a feed; extract from Feed entity:
$article = $em->getRepository('MyNewsBundle:Article')->findOneBy(array('feed'=>$this->getId(), 'link'=>$item->link()));
if (!$article) {
$article = new \My\NewsBundle\Entity\Article();
Any advice on how setter injection works or how to get that service in my entity would be greatly appreciated.
Entities are not managed nor created by the service container. Doctrine is responsible for translating database results into entities.
If you want to inject search service to your Article entity you have to do it manually. As it’s rather an optional dependency (you inject it with a setter) you should also check if it’s not null in your (post|pre)Persist hook.
Example: