godruoyi / easy-container
一个小型的 PHP 5.3 依赖注入容器,由 Laravel 容器扩展而来。
Requires
- php: >=8.1
- psr/container: ^2.0
Requires (Dev)
- phpunit/phpunit: ^10.0
This package is auto-updated.
Last update: 2024-08-31 00:32:09 UTC
README
为什么
当前更流行的 php
容器
Pimple
是一个简单而优秀的 php 5.3
容器,也是使用最广泛的服务容器,packagist 的安装量也高达 1000W+
。但是 Pimple
只是一个简单的服务容器,不支持许多功能,例如:
class Cache { public function __construct(Config $config){} } class Config { } // not support $cache = $container->make('Cache');
Pimple
不支持依赖参数的自动注入,当你需要依赖其他对象时,你只能实例化所需的参数。
Laravel Container
是最全面的服务容器,包括自动注入、加载、别名、标签等。但是官方不推荐在非 Laravel 项目中使用该组件。
如果你注意到了该组件下的
composer.json
文件,你会发现在它依赖于 illuminate/contracts 组件。(查看更多)
基于此,easy-container 应运而生,该项目代码在 Laravel Container 的基础上进行了大量依赖。(😄 😄)你可以像使用 Laravel Container
容器一样使用它。
安装
使用
你可以在 laravel.com 获取有关容器使用的更多帮助。
初始化容器。
$app = new Godruoyi\Container\Container;
以下文档由 laravel.com 支持并复制,请标明来源。
简单绑定
我们可以使用 bind
方法注册一个绑定,传递我们希望注册的类或接口名称以及一个返回该类实例的闭包。
$app->bind('HelpSpot\API', function ($app) { return new HelpSpot\API($app->make('HttpClient')); });
注意,所有匿名函数都接受服务容器实例作为参数。
绑定单例
使用 singleton
方法将类或接口绑定到容器中,该类或接口应只解决一次。一旦解决了单例绑定,随后的容器调用将返回相同的对象实例。
$app->singleton('HelpSpot\API', function ($app) { return new HelpSpot\API($app->make('HttpClient')); });
每次调用
$app['HelpSpot\API']
都会返回相同的对象。
绑定单例
使用 singleton
方法将类或接口绑定到容器中,该类或接口应只解决一次。一旦解决了单例绑定,随后的容器调用将返回相同的对象实例。
$api = new HelpSpot\API(new HttpClient);
$app->instance('HelpSpot\API', $api);
将接口绑定到实现
服务容器的一个非常强大的功能是将接口绑定到给定的实现。例如,假设我们有一个 EventPusher
接口和一个 RedisEventPusher
实现类。一旦我们为这个接口编写了 RedisEventPusher
实现类,我们可以像这样将其注册到服务容器中
$app->bind(
'App\Contracts\EventPusher',
'App\Services\RedisEventPusher'
);
此语句告诉容器,当需要 EventPusher
的实现时,应注入 RedisEventPusher
。现在我们可以在构造函数或其他服务容器注入依赖的地方为 EventPusher
接口进行类型提示。
use App\Contracts\EventPusher;
/**
* Create a new instance of the class, which will be injected into the App\Services\RedisEventPusher instance.
*
* @param EventPusher $pusher
* @return void
*/
public function __construct(EventPusher $pusher)
{
$this->pusher = $pusher;
}
解决
make
方法
您可以使用 make
方法从容器中解析类实例(无论对象需要什么类型的参数)。make
方法接受您希望解析的类或接口的名称。
$api = $app->make('HelpSpot\API');
我认为最重要的方法是mark
方法,你可以简单地使用“类型提示”的方式来添加依赖,容器会自动解析你需要的所有参数。
// Automatically parses the dependencies required by the UserController constructor $userController = $app->make(UserController::class); class UserController { public function __construct(UserRepository $users, HttpClient $client, $other = 'default') { } }
PSR-11
Laravel的服务容器实现了PSR-11接口。因此,你可以类型提示PSR-11容器接口以获取Laravel容器的实例
use Psr\Container\ContainerInterface;
$service = $app->get('Service');
监听
MIT