webdevcave / yadic
PHP的另一个依赖注入容器
v1.2
2024-07-06 02:20 UTC
Requires
- php: >=8.1
- psr/container: ^2.0
- psr/simple-cache: ^3.0
- webdevcave/directory-crawler: ^1.1
- webdevcave/simple-cache: ^1.0
Requires (Dev)
- phpunit/phpunit: ^10
- rregeer/phpunit-coverage-check: ^0.3.1
Provides
README
这是一个简单易用且功能强大的服务容器,提供了一种无缝自动化依赖注入的方法,具有自动绑定和对象注入功能。
composer require webdevcave/yadic
或者,您可以克隆仓库或直接下载源代码文件并将其包含到您的项目中。
使用方法
自动绑定
<?php require_once __DIR__.'/vendor/autoload.php'; use Webdevcave\Yadic\Annotations\Provides; use Webdevcave\Yadic\Annotations\Singleton; use Webdevcave\Yadic\ServiceContainer; interface StorageInterface { public function store(mixed $data): bool; } #[Provides('storage')] #[Provides(StorageInterface::class)] #[Singleton] class Storage implements StorageInterface { public function store(mixed $data): bool { //store data... return true; } } class MyController { public function __construct( private StorageInterface $storage ) { } public function save(): bool { return $this->storage->store('my data...'); } } $container = new ServiceContainer(); //No need to do this in a real world application: $container->addAlias(StorageInterface::class, Storage::class); //Use this instead: //$container->loadDefinitionsFromDirectory($directory, $namespace); //Loads annotations from classes declared in a PSR4 directory //var_dump($container->get('storage')->store($data)); var_dump($container->get(MyController::class)->save()); //bool(true)
使用自动绑定调用方法
$arguments = ['nonInjectableArgument' => 'value']; //optional $container->invoke([$instance, 'methodName'], $arguments);
注入
//Class declarations: use Webdevcave\Yadic\Annotations\ArrayOf; class Candidate { public function __construct( public ?string $name = null, public ?int $age = null, #[ArrayOf(Skill::class)] public array $skills = [] ) { } } class Skill { public function __construct( public string $title, ) { } } // Hydration example 1: $data = [ 'name' => 'John Doe', 'age' => 25, 'skills' => [ ['title' => 'PHP'], ['title' => 'Java'], ['title' => 'Rust'], ['title' => 'React'], ], ]; $instance = $container->hydrate(Candidate::class, $data); //Results output /* print_r($instance); This test printed output: Candidate Object ( [name] => John Doe [age] => 25 [skills] => Array ( [0] => Skill Object ( [title] => PHP ) [1] => Skill Object ( [title] => Java ) [2] => Skill Object ( [title] => Rust ) [3] => Skill Object ( [title] => React ) ) ) */ // Hydration example 2: $data = [ [ 'name' => 'Foo', //... ], [ 'name' => 'Bar', //... ] ]; $instances = $container->hydrate(Candidate::class, $data); //Results output /* print_r($instances); This test printed output: Array ( [0] => Candidate Object ( [name] => Foo //... ) [1] => Candidate Object ( [name] => Bar //... ) ) */
贡献
欢迎贡献!如果您发现任何问题或有改进建议,请打开GitHub上的问题或拉取请求。
许可证
本项目采用MIT许可证 - 有关详细信息,请参阅LICENSE文件。