rkulik / fractal
Fractal 的便捷包装器
1.0.0
2019-02-10 11:38 UTC
Requires
- php: ^7.2
- ext-json: *
- league/fractal: ^0.17.0
Requires (Dev)
- phpunit/phpunit: ^7
This package is auto-updated.
Last update: 2024-09-10 23:42:00 UTC
README
Fractal 的便捷包装器。
要求
此包需要 PHP 7.2 或更高版本。
安装
通过 composer
$ composer require rkulik/fractal
使用
由于此包包装了 Fractal,所以一般用法几乎相同。以下列出的示例展示了基本的工作流程。更多信息请参阅Fractal 文档。
项目示例
以下示例中,一个项目被转换并作为数组返回。转换是通过回调或类完成的。
转换器的回调
<?php require 'vendor/autoload.php'; $fractal = new \Rkulik\Fractal\Fractal(new \League\Fractal\Manager()); $product = [ 'id' => '123', 'name' => 'T-shirt', 'price' => '1290', 'brand_name' => 'Nike', 'gender' => 'm', ]; $transformer = function (array $product): array { return [ 'id' => (int)$product['id'], 'name' => $product['name'], 'price' => (int)$product['price'], 'brand' => $product['brand_name'], 'gender' => $product['gender'] === 'm' ? 'male' : 'female', ]; }; $item = $fractal->item($product, $transformer)->toArray();
转换器的类
使用类进行转换是推荐的方法,因为这些转换器易于重用。
<?php require 'vendor/autoload.php'; class Transformer extends \League\Fractal\TransformerAbstract { public function transform(array $product): array { return [ 'id' => (int)$product['id'], 'name' => $product['name'], 'price' => (int)$product['price'], 'brand' => $product['brand_name'], 'gender' => $product['gender'] === 'm' ? 'male' : 'female', ]; } } $fractal = new \Rkulik\Fractal\Fractal(new \League\Fractal\Manager()); $product = [ 'id' => '123', 'name' => 'T-shirt', 'price' => '1290', 'brand_name' => 'Nike', 'gender' => 'm', ]; $item = $fractal->item($product, new Transformer())->toArray();
集合示例
可以使用游标实现转换和分页集合,如下所示
<?php require 'vendor/autoload.php'; $fractal = new \Rkulik\Fractal\Fractal(new \League\Fractal\Manager()); $products = [ [ 'id' => '123', 'name' => 'T-shirt', 'price' => '1290', 'brand_name' => 'Nike', 'gender' => 'm', ], [ 'id' => '456', 'name' => 'Jacket', 'price' => '19900', 'brand_name' => 'Carhartt', 'gender' => 'f', ], [ 'id' => '789', 'name' => 'Trousers', 'price' => '3990', 'brand_name' => 'Only & Sons', 'gender' => 'f', ], ]; $transformer = function (array $product): array { return [ 'id' => (int)$product['id'], 'name' => $product['name'], 'price' => (int)$product['price'], 'brand' => $product['brand_name'], 'gender' => $product['gender'] === 'm' ? 'male' : 'female', ]; }; $cursor = new \League\Fractal\Pagination\Cursor(null, null, 2, 3); $collection = $fractal->collection([ $products[0], $products[1], ], $transformer)->setCursor($cursor)->toArray();
测试
$ composer test
变更日志
请参阅变更日志获取更多有关最近更改的信息。
贡献
有关详细信息,请参阅贡献指南。
安全
如果您发现任何与安全相关的问题,请通过电子邮件rene@kulik.io而不是使用问题跟踪器。
致谢
许可
MIT 许可证(MIT)。有关更多信息,请参阅许可文件。