alicemajere / wonderland-container
一个小巧简单的服务容器,可用于项目
1.1.0
2018-10-21 15:03 UTC
Requires
- php: >=7.2
- psr/container: ^1.0
- symfony/yaml: ^4.1
Requires (Dev)
- ockcyp/covers-validator: ^1.0
- phpunit/phpunit: ^6.5
- squizlabs/php_codesniffer: ^3.3
- symfony/var-dumper: ^4.1
This package is auto-updated.
Last update: 2024-09-22 04:20:59 UTC
README
Wonderland 容器
一个小巧简单的服务容器,可用于项目
最近更新
1.1.0 版本可用。请访问 发布页面 查看变更日志
安装
composer require alicemajere/wonderland-container
使用方法
初始化容器
创建容器的新的实例
$container = new Wonderland\Container\Container();
创建新的服务定义,并使用以下参数将其注册到容器中
- [STRING] 服务名称
- [STRING] 类名称
- [ARRAY] 构造函数参数
- [ARRAY] 方法调用及其参数。索引是方法名称,值是方法参数数组
// creating a service definition $definition = new Wonderland\Container\Service\ServiceDefinition( 'service.name', MyClass::class, ['args1', '@service.name2', ['array_args']], ['methodCall1' => ['args1', '@service.name3']] ); // register the definition into the container $container->addService($definition);
您也可以通过直接注入对象实例来创建新的服务
$instance = new MyClass(); $serviceInstance = new Wonderland\Container\Service\InstanceDefinition( 'service.name2', $instance ); // register the instance definition into the container $container->addServiceInstance(serviceInstance);
使用容器
检查容器中是否存在服务
if ($container->has('service.name')) { // code here }
检索服务实例
// retrieve the instance. Will create a new one if not created yet. Shared by default $instance = $container->get('service.name'); // retrieve a new instance of the service. Setting the second parameters to true will not retrieve the shared service instance $newInstance = $container->get('service.name', true); // retrieve the instance of the instance service definition. Setting the second parameter to true will do nothing if // the service is not a definition service but a instance definition service; only the shared instance will be retrieved $instance = $container->get('service.name2');
使用 YAML 文件加载配置
$container = new \Wonderland\Container\ServiceContainer(); $serviceLoader = new \Wonderland\Container\Configuration\ServiceLoader(new YamlParser()); // load every yml in a folder $container->loadServices($serviceLoader->loadDirectory(__DIR__ . '/Resource/')); // or a single file $container->loadServices($serviceLoader->loadFile(__DIR__ . '/Resource/test.yml'));
Yaml 文件示例
services: service.name: class: Wonderland\Container\Example\Yml\SampleClass arguments: - 'param1' - 'param2' calls: callMethod: - 'param11' - '@service.name3' service.name2: class: Wonderland\Container\Example\Yml\SampleClass arguments: - 'param3' - 'param4' calls: callMethod: - '@service.name' - 'param44' service.name3: class: \DateTime
示例
您可以在 examples
文件夹中查看更多库的运行示例。
先决条件
PHP >= 7.2
获取帮助
如果您在库中发现了错误或希望添加新功能,请在此存储库中打开问题或拉取请求!
作者
- Alice Praud - 初始工作 - AliceMajere