有两个实体 Restaurant 和 Users。餐厅实体与用户多对多关系,字段名favoriteBy。
<many-to-many field="favoriteBy" target-entity="UserBundle\Entity\Users" mapped-by="favoriteRestaurants"/>
我正在使用 JMS Serializer 和 FOSRestfulAPI。在餐厅列表 API 中,我必须公开一个额外的 bool 字段“isFavorite”,如果当前登录的用户在数组集合 favoriteBy 中,则该字段为真。
如何找到当前用户是否在实体内收藏了餐厅?
/**
* Get is favorited
* @JMS\VirtualProperty()
* @JMS\Groups({"listing", "details"})
*/
public function isFavorited()
{
// some logic in entity
return false;
}
我正在考虑的一种方法是将当前用户对象注入(inject)到实体和用户包含的方法中以找出答案,但它看起来不是很好的方法。 请建议我一些方法,或指导我正确的方向。
最佳答案
您可以按照描述 here in the doc 实现一个 EventSubscriberInterface .
例如:
use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
use JMS\Serializer\EventDispatcher\ObjectEvent;
...
class RestaurantSerializerSubscriber implements EventSubscriberInterface
{
protected $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public static function getSubscribedEvents()
{
return [
[
'event' => 'serializer.post_serialize',
'class' => Restaurant::class,
'method' => 'onPostSerialize',
],
];
}
public function onPostSerialize(ObjectEvent $event)
{
$visitor = $event->getVisitor();
$restaurant = $event->getObject();
// your custom logic
$isFavourite = $this->getCurrentUser()->isFavourite($restaurant);
$visitor->addData('isFavorited', $isFavourite);
}
/**
* Return the logged user.
*
* @return User
*/
protected function getCurrentUser()
{
return $this->tokenStorage->getToken()->getUser();
}
然后注册,以YML为例:
acme.restaurant_serializer_subscriber:
class: Acme\DemoBundle\Subscriber\RestaurantSerializerSubscriber
arguments: ["@security.token_storage"]
tags:
- { name: "jms_serializer.event_subscriber" }
希望对你有帮助
PS:您也可以拦截选择的序列化组,如果您需要该代码,请告诉我。
关于php - Symfony Restful API - 公开当前登录用户喜欢的虚拟属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39032372/