joshbrw / entity-transformers
Installs: 4 889
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
Type:llibrary
Requires
- php: >=7.0
- illuminate/support: ^5.4
Requires (Dev)
- phpunit/phpunit: ^6.1
This package is auto-updated.
Last update: 2024-11-28 23:39:59 UTC
README
This project provides a base class for standardised Entity Transformers, which can be used to morph entities/objects into arrays. The primary use for these transformers is API Responses.
Example
<?php use Joshbrw\EntityTransfomers\EntityTransformer; class UserTransformer extends EntityTransformer { /** * Transform a single Entity into an array * @param mixed $entity Entity instance * @return array */ public function transform($entity): array { return [ 'id' => $entity->id, 'title' => $entity->title, 'first_name' => $entity->first_name, 'last_name' => $entity->last_name, 'email' => $entity->email, 'permissions' => $entity->permissions, 'age' => $this->getTransformationFlag('showAge') === true ? $entity->age : null ]; } }
Which can then be used to either transform a single entity:
$transformer = new UserTransformer; $response = $transformer->transform($user);
or to transform an Illuminate Collection of entities.
$users = new \Illuminate\Support\Collection($data); $transformer = new UserTransformer; $response = $transformer->transform($users);
You can also use Transformation Flags to set conditions at runtime, such as:
$transformer = new UserTransformer; $transformer->setTransformationFlag('showAge', true); $response = $transformer->transform($user);