Simpleservicecontainer一个简单的php5.3依赖注入容器。项目地址:https://github.com/godruoyi/easy-container为什么目前流行PHP容器:PimpleLaravelContainer其他依赖注入容器Pimple是一个简单优秀的PHP5.3容器,也是目前使用最多的服务容器,在packagist安装量也达到了1000w+。但是Pimple只是一个简单的服务容器,不支持很多特性比如:classCache{publicfunction__construct(Config$config){}}classConfig{}//不支持$cache=$container->make('Cache');Pimple不支持自动注入依赖参数。当你需要的对象依赖于其他对象时,你只能依次实例化需要的参数。LaravelContainer是目前最全面的服务容器,支持的功能更全面,包括自动注入、依赖加载、别名、TAG等。但官方不推荐在非laravel项目中使用该组件。如果你关注这个组件下的composer.json文件,你会发现它依赖于illuminate/contracts组件。(见)基于此诞生了easy-container,项目代码大部分依赖于LaravelContainer。你可以像Laravel容器一样使用它。安装composer需要godruoyi/easy-container才能使用你可以去Laravel-china获取更多关于使用容器的帮助。初始化容器$app=newGodruoyi\Container\Container;以下文档均由laravel-china支持,转载请注明出处。简单绑定可以通过bind方法注册,传递我们要注册的类或接口的名称然后返回类实例的Closure:$app->bind('HelpSpot\API',function($app){returnnewHelpSpot\API($app->make('HttpClient'));});请注意,所有匿名函数都接受一个服务容器实例作为参数。绑定单例方法将一个类或接口绑定到一个只能解析一次的容器中。解析绑定的单例后,相同的对象实例将在后续调用中返回到容器:$app->singleton('HelpSpot\API',function($app){returnnewHelpSpot\API($app->make('HttpClient'));});每次调用$app['HelpSpot\API']都会返回统一对象。绑定实例您还可以使用实例方法将现有对象实例绑定到容器。给定的实例将始终在后续调用中返回到容器:$api=newHelpSpot\API(newHttpClient);$app->instance('HelpSpot\API',$api);将接口绑定到实现服务容器的一个强大功能是将接口绑定到给定的实现。例如,如果我们有一个EventPusher接口和一个RedisEventPusher实现。写完接口的RedisEventPusher实现后,我们就可以在服务容器中注册了,像这样:$app->bind('App\Contracts\EventPusher','App\Services\RedisEventPusher');这相当于告诉容器:当一个类需要实现EventPusher时,应该注入RedisEventPusher。现在我们可以使用类型提示在构造函数中或任何其他通过服务容器注入依赖项的地方注入EventPusher接口:useApp\Contracts\EventPusher;/***创建一个新的类实例,其中App\Services将是注入\RedisEventPusher的一个实例。**@paramEventPusher$pusher*@returnvoid*/publicfunction__construct(EventPusher$pusher){$this->pusher=$pusher;}解析make方法可以使用make方法解析出类实例容器(无论对象需要什么类型的参数)。make方法接受要解析的类或接口的名称:$api=$app->make('HelpSpot\API');mark方法在我看来是最重要的方法,你可以简单地在Adddependenciestoconstructorsofclassesbythecontainerresolved中使用“typehints”,容器会自动解析你需要的所有参数。//自动解析UserController构造函数需要的依赖$userController=$app->make(UserController::class);classUserController{publicfunction__construct(UserRepository$users,HttpClient$client,$other='default'){}}PSR-11Laravel的服务容器实现了PSR-11接口。因此,您可以键入提示PSR-11容器接口来获取Laravel容器的实例:usePsr\Container\ContainerInterface;$service=$app->get('Service');LISTENMITTThankslaravel-china
