estasi / plugin-manager
用于动态连接类的插件管理器
1.1.0
2020-06-08 08:37 UTC
Requires
- php: ^7.4
- estasi/filter: ^1
- estasi/utility: ^1
- php-ds/php-ds: dev-master
- psr/container: dev-master
This package is auto-updated.
Last update: 2024-09-08 18:05:52 UTC
README
PluginManager 是一个专门的服务管理器,用于创建特定类型的统一对象,例如 Estasi\Validator 和 Estasi\Filter 使用相应的专用 PluginManager。
安装
使用 composer 安装
composer require estasi/plugin-manager
要求
- PHP 7.4 或更高版本
- 数据结构:
composer require php-ds/php-ds
Polyfill 是与 estasi/plugin-manager 包一起安装的。 - 容器接口:
composer require psr/container
它与 estasi/plugin-manager 包一起安装。
用法
创建插件管理器
要创建插件管理器,首先需要创建一个新类,该类扩展了 Estasi\PluginManager\Abstracts\PluginManager
<?php declare(strict_types=1); use Estasi\PluginManager\{Abstracts,Interfaces,Plugin,PluginsList}; class MyPluginManager extends Abstracts\PluginManager { public function getInstanceOf(): ?string { return 'MyBasicClass'; } public function getPlugins(): Interfaces\PluginsList { return new PluginsList( new Plugin(MyFirstClass::class, ['first', 'First', /*... aliases of class*/]), new Plugin('MySecondClass', ['second', 'Second', /*... aliases of class */], new MyFactoryForSecondClass()), ); } }
使用 PluginManager
然后您可以从 PluginManager 创建一个类
<?php declare(strict_types=1); $myPluginManager = new MyPluginManager(); // Creating a object without constructor parameters $myFirstClass = $myPluginManager->get(MyFirstClass::class); // or $myFirstClass = $myPluginManager->build('first'); // With the parameters necessary (or optional) to create the object $myFirstClass = $myPluginManager->build('First', ['foo' => 'bar', 'bar' => 'foo']);
注意
创建对象时,默认使用的工厂使用修改过的 \ReflectionClass
类。其特殊功能是所有构造函数参数都必须使用驼峰命名法。
如果构造函数有 options
参数,则传递给创建类对象的全部参数,但未在构造函数中找到的参数将落入此参数。如果传递给创建类的参数中没有 options
,则忽略它们。
如果未在传递的值中找到,则用默认参数值替换。
<?php declare(strict_types=1); class MyFirstClass { public function __construct($foo, $bar = 'foo', iterable $options = null) { // your code } }
<?php declare(strict_types=1); $myPluginManager = new MyPluginManager(); // "foo" required parameter. if it is not present, the \OutOfBoundsException exception will be created // the optional "bar" parameter will get the default value "foo" // the undeclared "baz" parameter will be included in the "options" parameter: ["baz" = "baz"] $myFirstClass = $myPluginManager->build(MyFirstClass::class, ['foo' => 'bar', 'baz' => 'baz']); // the same thing // if you use this method all undeclared parameters will not be used when creating the object // and will not be included in "options" $myFirstClass = $myPluginManager->build(MyFirstClass::class, ['foo' => 'bar', 'options' => ['baz' => 'baz'], 'param' => 'value']);
许可
本包的所有内容均受BSD-3-Clause 许可许可。