How do I create a custom exclusion strategy for JMS Serializer that allows me to make run-time decisions about whether to include a particular field?

后端 未结 2 1723
小蘑菇
小蘑菇 2020-12-31 19:42

As the title says, I am trying to make a run-time decision on whether or not to include fields in the serialization. In my case, this decision will be based on permissions.<

2条回答
  •  伪装坚强ぢ
    2020-12-31 20:30

    As of jms/serializer 1.4.0, the symfony expression language is integrated in its core.

    The feature is documented at http://jmsyst.com/libs/serializer/master/cookbook/exclusion_strategies#dynamic-exclusion-strategy and this allows to use runtime exclusion strategies.

    An example taken from the documentation is:

    class MyObject
    {
        /**
         * @Exclude(if="service('user_manager_service').getSomeRuntimeData(object)")
         */
        private $name;
    
       /**
         * @Expose(if="service('request_stack').getCurrent().has('foo')")
         */
        private $name2;
    }
    

    I this example, the services user_manager_service and request_stack are invoked at runtime, and depending on the return (true or false), the property will be exposed or not.

    With the same expression language, as of 1.6.0 is possible also to use virtual properties via expression language. Documented at http://jmsyst.com/libs/serializer/master/reference/annotations#virtualproperty allows to add on the fly data coming from external services

提交回复
热议问题