I have an entity Acme\Bundle\Entity\Author
which has a one to many relationship to Acme\Bundle\Entity\Article
and I have two JMS serializer event subscribers for both entities.
Subscriber for Acme\Bundle\Entity\Author
;
acm.author_serialization_listener:
class: Acm\Bundle\Listener\AuthorSerializationListener
tags:
- { name: jms_serializer.event_subscriber }
class AuthorSerializationListener implements EventSubscriberInterface
{
/**
* @inheritdoc
*/
public static function getSubscribedEvents()
{
return array(
array('event' => 'serializer.pre_serialize', 'class' => 'Acme\Bundle\Entity\Author' 'method' => 'onPreSerialize'),
);
}
public function onPreSerialize(PreSerializeEvent $event)
{
if($event->getObject() instanceof Author) {
return;
}
}
}
Subscriber for Acme\Bundle\Entity\Article
;
acm.article_serialization_listener:
class: Acm\Bundle\Listener\ArticleSerializationListener
tags:
- { name: jms_serializer.event_subscriber }
class ArticleSerializationListener implements EventSubscriberInterface
{
/**
* @inheritdoc
*/
public static function getSubscribedEvents()
{
return array(
array('event' => 'serializer.pre_serialize', 'class' => 'Acme\Bundle\Entity\Article' 'method' => 'onPreSerialize'),
);
}
public function onPreSerialize(PreSerializeEvent $event)
{
if($event->getObject() instanceof Article) {
return;
}
}
}
The problem occurs in the onPreSerialize
function when serializing Author
along with related Article
s in the ArticleSerializationListener
subscriber class where it injects Proxies\__CG__\Acme\Bundle\Entity\Article instead of Acme\Bundle\Entity\Article entities which lead to exclude the related Article
entities. Is there something I am doing wrong or is there a workaround for this?
Instead of
get_class
you should simply use the operatorinstanceof
because the proxies inherit from the entities. You compare two strings.Sidenode: Also the operator
!===
does not exist.