Reputation: 792
I have an Entity UserProfile that contains a field profileImage, that ist a fileKey
When my REST Controller gets called and needs to render a Board, that contains somwhere a UserProfile Object, i want that it returns a complete URL with the fileKey.
As far as i cannot use Services etc. in Entities, i thought if its possible to call a Service through the Accessor?
http://jmsyst.com/libs/serializer/master/reference/annotations#accessor
How could i call a e.g. Service within an accessor? Or are there any other possibilities?
Upvotes: 1
Views: 682
Reputation: 37058
To use a service in the accessor you will need to inject the service into the entity, or use a static facade to call a service. This is not advisable as it tightly couples the entity with the service.
Instead consider to use a custom type for the property, e.g. ProfileImageUrl, and inject the service to the handler. This way the image name transformation shifts to the representation layer, where it belongs.
The handler may look like following:
class ProfileImageUrlHandler implements SubscribingHandlerInterface
{
public function __construct(Service $service)
{
$this->service = $service;
parent::__construct();
}
public static function getSubscribingMethods()
{
return array(
array(
'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
'format' => 'json',
'type' => 'FQCN\Of\ProfileImageUrl',
'method' => 'serializeProfileImageUrlToJson',
),
);
}
public function serializeProfileImageUrlToJson(JsonSerializationVisitor $visitor, ProfileImageUrl $imageNAme, array $type, Context $context)
{
return $this->service->buildUrl($imageName);
}
}
In Symfony you can use any service as a handler by tagging it as docummented here:
<service id="service_id" class="Service">
<tag name="jms_serializer.handler"
type="FQCN\Of\ProfileImageUrl"
direction="serialization"
format="json"
method="imageToUrl" />
</service>
And finally, you have an option to use the service in the post_rserialize event. The documentation suggests the links should be added there, but to my taste it lacks visibility, and smells like magic.
Upvotes: 2