php - Include simple fields based on context in Fractal -
i using fractal library transform book
object json using simple transformer:
class booktransformer extends \league\fractal\transformerabstract { public function transform(book $book) { return [ 'name' => $book->getname() // ... ]; } }
and performing transformation follows.
$book = new book('my awesome book'); $resource = new \league\fractal\resource\item($book, new booktransformer()); $fractal = new \league\fractal\manager(); $fractal->setserializer(new \league\fractal\serializer\arrayserializer()); $json = $fractal->createdata($resource)->tojson();
this works great. however, have fields on book
object should not included, because depends on context transformation done in. in particular use case, json returned ajax requests public website should not include sensitive information, while should case when data requested admin backend.
so, let's book has topsecretvalue
field, string. field should not included in 1 transformation, should included in another. took @ transformer includes, , played around it, works resources. in case, need somehow include different fields (not resources) different contexts. have been digging around , not find in fractal library me, maybe missing something?
i came working solution, not prettiest world has ever seen. having basebooktransformer
transforms fields should included, can extend transformer add fields other contexts, e.g. adminbooktransformer
or topsecretvaluebooktransformer
, below.
class adminbooktransformer extends booktransformer { public function transform(book $book) { $arr = parent::transform($book); $arr['author'] = $book->gettopsecretvalue(); return $arr; } }
this works fine, although not "clean" using includes (if possible), because have use different transformer.
so question is: there in fractal enables me accomplish in simpler/cleaner way, or there better way it, fractal way or not?
Comments
Post a Comment