nikolas-lada / reflection-factory
一个微小的静态工厂类,通过反射加载参数并将它们注入构造函数。
v1.0.0
2020-02-02 18:12 UTC
Requires
- php: >= 7.1
Requires (Dev)
- nette/tester: ^2.0
This package is auto-updated.
Last update: 2024-09-29 04:48:57 UTC
README
通过反射加载参数并将它们注入构造函数的工厂类。
安装
composer require nikolas-lada/reflection-factory
它需要 PHP 版本 7.1 或更高。
用法
对于 \stdClass
use \NikolasLada\ReflectionFactory\ReflectionFactory; $data = new \stdClass; /** * no matter of property order */ $data->created = '2018-03-20 12:00:00'; $data->id = 1; $data->updated = \null; $beforeCreate = function() use ($data) { $data->created = new \DateTime($data->created); if (!\is_null($data->updated)) { $data->updated = new \DateTime($data->updated); } return $data; }; $article = ReflectionFactory::createFromStdClass( \NikolasLada\ReflectionFactory\Tests\Domain\Article::class, $data, $beforeCreate ); // or $article = ReflectionFactory::create( \NikolasLada\ReflectionFactory\Tests\Domain\Article::class, $data, $beforeCreate );
对于数组
use \NikolasLada\ReflectionFactory\ReflectionFactory; $data = []; /** * The createFromArray method depends on order items in array! */ $data['id'] = 1; $data['created'] = '2018-03-20 12:00:00'; $data['updated'] = '2018-03-20 12:01:13'; $data['created'] = new \DateTime($data['created']); if (!\is_null($data['updated'])) { $data['updated'] = new \DateTime($data['updated']); } $article = ReflectionFactory::createFromArray( \NikolasLada\ReflectionFactory\Tests\Domain\Article::class, $data ); // or $beforeCreate = function() use ($data) { $data['created'] = new \DateTime($data['created']); return $data; }; $article = ReflectionFactory::create( \NikolasLada\ReflectionFactory\Tests\Domain\Article::class, $data, $beforeCreate );
许可证
Reflection factory 库是开源软件,许可协议为