ganyariya / hako
一个超级简单的DI容器
v0.1.1
2022-08-07 07:52 UTC
Requires
- psr/container: ^2.0
Requires (Dev)
- phpstan/phpstan: ^1.8
- phpunit/phpunit: ^9.5
- squizlabs/php_codesniffer: ^3.7
- vimeo/psalm: ^4.26
This package is auto-updated.
Last update: 2024-09-07 12:22:24 UTC
README
PHP的超级简单DI容器 📦(基于PSR-11)。
📦 安装方法
composer require ganyariya/hako
📦 示例
详细示例可以在tests中查看。
设置/获取
<?php use Ganyariya\Hako; use Ganyariya\Hako\Container\Container; use Psr\Container\ContainerInterface; /** * Suppose that your some interface and class are already defined. * For example, Your UserRepositoryInterface, UserRepository, MasterRepositoryInterface, and MasterRepository are defined. */ $container = new Container(); $container->set("Hello", "world!"); // Pattern1: Hako\fetch can automatically resolve dependencies using builtin \Reflection. $container->set(UserRepositoryInterface::class, Hako\fetch(UserRepository::class)); $container->set(MasterRepositoryInterface::class, Hako\fetch(MasterRepository::class)); // Pattern2: Your Self Injection $container->set(UserRepositoryInterface::class, function(ContainerInterface $c) { /** * You can pre-set up objects at here. */ return new UserRepository( $c->get(MasterRepositoryInterface::class); ); }); assert($container->get("Hello") === "world!"); assert($container->get(UserRepositoryInterface::class) instanceof UserRepository); /** * After setting up the Container, pass the Container to a WebFramework such as Slim or Laravel. * https://slim.php.ac.cn/docs/v4/concepts/di.html * /
容器构建器
<?php use Ganyariya\Hako; use Ganyariya\Hako\Container\ContainerBuilder; $builder = new ContainerBuilder(); $builder->addDefinitions([ GetsInterface::class => Hako\fetch(GetsInteractor::class), MasterRepositoryInterface::class => Hako\fetch(MasterRepository::class), ]); $builder->addDefinitions([ UserRepositoryInterface::class => Hako\fetch(UserRepository::class) ]); // From definitions, create container. $container = $builder->build(); /** @var GetsController $controller */ $controller = $container->get(GetsController::class); /** * After setting up the Container, pass the Container to a WebFramework such as Slim or Laravel. * https://slim.php.ac.cn/docs/v4/concepts/di.html */