A fork and re-write of samj/fractal-bundle to provide Fractal integration with the Symfony Framework.
- PHP 8.0+
- symfony/framework-bundle 5.2+
Install using composer, or checkout / pull the files from github.com.
- composer require somnambulist/fractal-bundle
Add the SomnambulistFractalBundle
to your bundles.php
list if not registered by Symfony Flex.
This bundle allows auto-wiring / auto-configuring transformers as services. This allows you to take advantage of Symfonys container to resolve dependencies and reference transformers by class name (or service alias).
So long as the transformer extends from League\Fractal\TransformerAbstract
or is tagged with
somnambulist.fractal_bundle.transformer
, it will be available to the Fractal Manager instance.
services:
App\Http\Api\Transformers\:
resource: '%kernel.project_dir%/Http/Api/Transformers/'
If transformers don't extend the TransformerAbstract
be sure to tag them:
services:
App\Http\Api\Transformers\:
resource: '%kernel.project_dir%/Http/Api/Transformers/'
tags: ['somnambulist.fractal_bundle.transformer']
Note: if your transformer is not registered as a service or passed as a valid callable or
instance of TransformerAbstract
, this library will raise an exception.
For example: to add an auth check to a UserTransformer
(example from samj readme):
use League\Fractal\TransformerAbstract;
class UserTransformer extends TransformerAbstract
{
public function __construct(private AuthorizationChecker $authorizationChecker)
{
}
public function transform(User $user)
{
$data = [
'id' => $user->id(),
'name' => $user->name(),
];
if ($this->authorizationChecker->isGranted(UserVoter::SEE_EMAIL, $user)) {
$data['email'] = $user->email();
}
return $data;
}
}
Reference the transformer by either a service alias name, or the class name:
$resource = new Collection($users, UserTransformer::class);
This works in includes as well:
public function includeFriends(User $user)
{
return $this->collection($user->friends(), UserTransformer::class);
}
Look in the sample application for some further examples.
PHPUnit 9+ is used for testing. Run tests via vendor/bin/phpunit
.