saritasa/transformers
最新稳定版本:1.2.2
Composer 安装命令:
composer require saritasa/transformers
包简介
Saritasa custom transformers on top of League/Fractal Library
关键字:
README 文档
README
Custom Data transformers on top of League/Fractal library.
See Fractal documentation at http://fractal.thephpleague.com/
Laravel 5.x/6.x
Install the saritasa/transformers package:
$ composer require saritasa/transformers
If you use Laravel 5.4 or less,
or 5.5+ with package discovery disabled,
add the TransformersServiceProvider service provider in config/app.php:
'providers' => array( // ... Saritasa\Transformers\TransformersServiceProvider::class, )
This is required for localization to work properly.
Available transformers
IDataTransformer
Interface to unlink dependency from League/Fractal library. Ensure, that every transformer implementation in this library has this interface.
Example:
class AnotherTransformerWrapper implements IDataTransformer { public function __construct(IDataTransformer $nestedTransformer) { ... } }
BaseTransformer
When you just need to convert model to JSON response via Dingo/Api methods, and have no specific formatting requirements, you can just use BaseTransformer. It calls Arrayable->toArray() method. Thus, for Eloquent model result will consist of fields, described as $visible and not $hidden. Additionally converts fields, enumerated in $dates to ISO8061 format.
Example:
class User extends \Illuminate\Database\Eloquent\Model { // "full_name" is a property calculated from first_name and last_name protected $visible = ['full_name', 'created_at']; protected $hidden = ['email', 'password']; protected $dates = ['created_at', 'updated_at', 'birthday']; } class UserController extends BaseApiController { public function myProfile(): \Dingo\Api\Http\Response { $user = $this->user(); // Returns Eloquent model return $this->response->item($user, new BaseTransformer); // Output will be JSON // { "full_name": "Ivan Ivanov", "created_at": "2017-04-12T23:20:50.52Z" } } } $user = User::find($userId);
ObjectFieldsTransformer
Will output requested fields to result, regardless they described as $hidden or $visible in Eloquent model
Example:
class User extends \Illuminate\Database\Eloquent\Model { // "full_name" is a property calculated from first_name and last_name protected $visible = ['full_name', 'created_at']; protected $hidden = ['email', 'password']; protected $dates = ['created_at', 'updated_at', 'birthday']; } class UserController extends BaseApiController { public function myProfile(): \Dingo\Api\Http\Response { $user = $this->user(); // Returns Eloquent model $profileTransformer = new ObjectFieldsTransformer('first_name', 'last_name', 'email', 'birthday'); return $this->response->item($user, $profileTransformer); // Output will be JSON // { "first_name": "Ivan", "last_name": "Ivanov", "email": "ivanov@mail.ru", "birthday": "1985-04-12T00:00:00.00Z" } } } $user = User::find($userId);
CombineTransformer
Apply multiple transformers in order of arguments;
Example:
class UserProfileTransformer extends CombineTransformer { public function __construct() { parent::__construct( new PreloadUserAvatarTransformer(), new PreloadUserSettingsTransformer() ); } }
LimitFieldsTransformer
Result will first apply ->toArray() method (which acts, respecting Eloquent's $visible and $hidden fields), then limits output to selected fields. This, hidden fields will not get in output, even if listed.
Example:
class User extends \Illuminate\Database\Eloquent\Model { protected $visible = ['full_name', 'created_at']; protected $hidden = ['email', 'password']; protected $dates = ['created_at', 'updated_at', 'birthday']; } class UserController extends BaseApiController { public function myProfile(): \Dingo\Api\Http\Response { $user = $this->user(); // Returns Eloquent model $publicProfileTransformer = new LimitFieldsTransformer('full_name', 'birthday'); return $this->response->item($user, new BaseTransformer); // Output will be JSON // { "full_name": "Ivan Ivanov" } } } $user = User::find($userId);
Exceptions
TransformException
Should be thrown by class, implementing IDataTransformer, if it encounters data, that cannot be transformed.
Example:
function transform(Arrayable $data) { if (!$data->author) { new TransformException($this, "Author may not be empty"); } // ... }
TransformTypeMismatchException
Should be thrown, if your transformer expects model of a certain type, but gets another class.
class UserTransformer extends BaseTransformer { public function transform(Arrayable $model) { if (!$model instanceof User) { throw new TransformTypeMismatchException($this, User::class, get_class($model)); } return transformUser($model); } private function transformUser(User $user) { ... // Handle strong-typed model } }
Utility Classes
DtoModel
Allows you to use pure DTO models instead of Eloquent, while using Fractal for collection transformation.
Contributing
- Create fork, checkout it
- Develop locally as usual. Code must follow PSR-1, PSR-2 - run PHP_CodeSniffer to ensure, that code follows style guides
- Cover added functionality with unit tests and run PHPUnit to make sure, that all tests pass
- Update README.md to describe new or changed functionality
- Add changes description to CHANGES.md file. Use Semantic Versioning convention to determine next version number.
- When ready, create pull request
Make shortcuts
If you have GNU Make installed, you can use following shortcuts:
make cs(instead ofphp vendor/bin/phpcs) - run static code analysis with PHP_CodeSniffer to check code stylemake csfix(instead ofphp vendor/bin/phpcbf) - fix code style violations with PHP_CodeSniffer automatically, where possible (ex. PSR-2 code formatting violations)make test(instead ofphp vendor/bin/phpunit) - run tests with PHPUnitmake install- instead ofcomposer installmake allor justmakewithout parameters - invokes described above install, cs, test tasks sequentially - project will be assembled, checked with linter and tested with one single command
Resources
saritasa/transformers 适用场景与选型建议
saritasa/transformers 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 25.54k 次下载、GitHub Stars 达 1, 最近一次更新时间为 2017 年 04 月 07 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「api」 「fractal」 「transformers」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 saritasa/transformers 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 saritasa/transformers 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 saritasa/transformers 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
CakePHP view builder utilizing Fractal library for entities transformation
Simple laravel eloquent models transformers.
Wraper for spatie fractal package
Collection handling in PHP
A PSR-7 compatible library for making CRUD API endpoints
Smokescreen is a PHP library for transforming and serializing data such as API responses.
统计信息
- 总下载量: 25.54k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 31
- 依赖项目数: 2
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2017-04-07