gpt4 book ai didi

symfony - 如何为 JMS Serializer 创建自定义排除策略,以便我可以在运行时决定是否包含特定字段?

转载 作者:行者123 更新时间:2023-12-02 16:45:46 28 4
gpt4 key购买 nike

正如标题所示,我正在尝试在运行时决定是否在序列化中包含字段。就我而言,此决定将基于权限。

我正在使用 Symfony 2,所以我想做的是添加一个名为 @ExcludeIf 的附加注释,它接受安全表达式。

我可以处理元数据的注释解析和存储,但我无法了解如何将自定义排除策略与库集成。

有什么建议吗?

注意:排除策略是 JMS 代码库中的实际构造,我只是无法找出在其他策略之上集成额外策略的最佳方法

PS:我之前曾问过这个问题,并被指出要使用组。由于各种原因,这对于我的需求来说是一个非常糟糕的解决方案。

最佳答案

您只需创建一个实现JMS\Serializer\Exclusion\ExclusionStrategyInterface的类

<?php

namespace JMS\Serializer\Exclusion;

use JMS\Serializer\Metadata\ClassMetadata;
use JMS\Serializer\Metadata\PropertyMetadata;
use JMS\Serializer\Context;

interface ExclusionStrategyInterface
{
/**
* Whether the class should be skipped.
*
* @param ClassMetadata $metadata
*
* @return boolean
*/
public function shouldSkipClass(ClassMetadata $metadata, Context $context);

/**
* Whether the property should be skipped.
*
* @param PropertyMetadata $property
*
* @return boolean
*/
public function shouldSkipProperty(PropertyMetadata $property, Context $context);
}

就您的情况而言,您可以在 shouldSkipProperty 方法中实现自己的自定义逻辑,并始终为 shouldSkipClass 返回 false

实现示例可以在 JMS/Serializer repository 中找到

我们将在下面将创建的服务引用为 acme.my_exclusion_strategy_service

<小时/>

在您的 Controller 操作中:

<?php

use Symfony\Component\HttpFoundation\Response;
use JMS\Serializer\SerializationContext;

// ....

$context = SerializationContext::create()
->addExclusionStrategy($this->get('acme.my_exclusion_strategy_service'));

$serial = $this->get('jms_serializer')->serialize($object, 'json', $context);

return new Response($serial, Response::HTTP_OK, array('Content-Type' => 'application/json'));

或者如果您使用的是 FOSRestBundle

<?php

use FOS\RestBundle\View;
use JMS\Serializer\SerializationContext;

// ....

$context = SerializationContext::create()
->addExclusionStrategy($this->get('acme.my_exclusion_strategy_service'))

$view = new View($object);
$view->setSerializationContext($context);

// or you can create your own view factory that handles the creation
// of the context for you

return $this->get('fos_rest.view_handler')->handle($view);

关于symfony - 如何为 JMS Serializer 创建自定义排除策略,以便我可以在运行时决定是否包含特定字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21916450/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com