mathieutu / exporter
从所有对象和数组中导出您需要的属性。
3.3.2
2024-03-10 00:45 UTC
Requires
- php: >= 8.1
- ext-json: *
- illuminate/collections: *
Requires (Dev)
- phpunit/phpunit: ^10.0.11
- squizlabs/php_codesniffer: ^3.7.1
README
安装
使用 composer 安装此软件包
composer require mathieutu/exporter
用例
因为图片胜过千言万语
Exporter 软件包让您编写如下代码
而不是这样
例如,我经常与 Laravel Eloquent 资源一起使用它,或者将其作为 Symfony Normalizer 的更容易的替代方案
使用方法
在您的类中使用 \MathieuTu\Exporter\Exporter
特性。您还可以直接在基本数组或对象上使用 \MathieuTu\Exporter\ExporterService::exportFrom($exportable, $attributes)
静态方法,或者如果您不能添加特性。
您可以使用数组、具有 ArrayAccess
接口的对象或任何标准对象进行导出。
响应将是一个 Laravel Collection(但您绝对不需要 Laravel,此软件包完全与框架无关)。如果您不知道如何使用集合,您可以使用它像数组一样,或者使用 toArray()
方法获取一个真正的集合。
示例
(您可以在 软件包测试 中找到所有这些示例以及更多内容)
对于示例,以及为了涵盖使用此软件包的所有可能方式,我们将考虑此对象作为输入
$object = new class { use \MathieuTu\Exporter\Exporter; public $foo = 'testFoo'; private $bar = ['bar1' => 'testBar1', 'bar2' => 'testBar2', 'bar3' => 'testBar3']; public $baz = [ (object) ['baz1' => 'baz1A', 'baz2' => 'baz2A', 'baz3' => 'baz3A'], (object) ['baz1' => 'baz1B', 'baz2' => 'baz2B', 'baz3' => 'baz3B'], (object) ['baz1' => 'baz1C', 'baz2' => 'baz2C', 'baz3' => 'baz3C'], ]; public function testWithParam(string $param): string { return 'test' . $param; } public function test(): string { return 'test' . date("l"); } public function getBar(): array { return $this->bar; } };
和一个标准数组作为输出(在注释中),而不是一个集合(由 $collection->toArray()
方法生成的结果)。
导出公共和私有(带有获取器)根属性
$object->export(['foo']); // ['foo' => testFoo] $object->export(['foo', 'bar']); /* [ 'foo' => testFoo, 'bar' => ['bar1' => 'testBar1', 'bar2' => 'testBar2'], ] */
从嵌套数组/对象导出
$object->export(['bar' => ['bar2', 'bar3']]); /* [ 'bar' => [ 'bar2' => testBar2', 'bar3' => testBar3', ], ] */
$object->export(['bar' => 'bar1']); // ['bar' => 'testBar1']
$object->export(['bar.bar1']); // ['bar.bar1' => 'testBar1']
$object->export(['baz' => ['*' => ['baz1', 'baz3']]]); /* [ 'baz' => [ ['baz1' => 'baz1A', 'baz3' => 'baz3A'], ['baz1' => 'baz1B', 'baz3' => 'baz3B'], ['baz1' => 'baz1C', 'baz3' => 'baz3C'], ], ] */
设置别名作为键
$object->export(['foo', 'bar.bar2 as secondBar']); /* [ 'foo' => testFoo, 'secondBar' => 'testBar2', ] */
导出函数的结果
$object->export(['testWithParam(Mathieu)']); // ['testWithParam' => testMathieu] $object->export(['test()']); // ['test' => testFriday]
许可协议
此 Exporter 软件包是一个开源软件,根据MIT 许可协议授权。
贡献
问题和 PR 显然受到欢迎并受到鼓励,无论是为了错误还是新功能以及文档。添加的每一块代码都应该完全经过测试,但我们可以一起做这件事,所以请不要为此感到害怕。