chillerlan / php-settings-container
不可变设置对象的容器类。不是DI容器。
3.2.1
2024-07-16 11:13 UTC
Requires
- php: ^8.1
- ext-json: *
Requires (Dev)
- phpmd/phpmd: ^2.15
- phpstan/phpstan: ^1.11
- phpstan/phpstan-deprecation-rules: ^1.2
- phpunit/phpunit: ^10.5
- squizlabs/php_codesniffer: ^3.10
README
设置对象的容器类 - 将配置逻辑与应用程序解耦!不是DI容器。
SettingsContainerInterface
提供了具有魔法获取器和设置器的不可变属性和一些额外功能。
文档
安装
需要 composer
composer.json (注意:将 dev-main
替换为 版本约束,例如 ^3.0
- 请参阅 版本 以获取有效版本)
{ "require": { "php": "^8.1", "chillerlan/php-settings-container": "dev-main" } }
盈利!
用法
SettingsContainerInterface
(包裹在 SettingsContainerAbstract
中)为不可变对象属性提供插件功能,并添加一些额外功能,如加载/保存JSON、数组等。它接受一个 iterable
作为唯一的构造函数参数,并在调用时对每个使用的特性调用具有特性名称的方法(MyTrait::MyTrait()
)。
可以在 rules-magic-access.neon
中找到排除由在 SettingsContainerInterface
上访问魔法属性而产生的PHPStan规则集。
简单用法
class MyContainer extends SettingsContainerAbstract{ protected string $foo; protected string $bar; }
// use it just like a \stdClass (except the properties are fixed) $container = new MyContainer; $container->foo = 'what'; $container->bar = 'foo'; // which is equivalent to $container = new MyContainer(['bar' => 'foo', 'foo' => 'what']); // ...or try $container->fromJSON('{"foo": "what", "bar": "foo"}'); // fetch all properties as array $container->toArray(); // -> ['foo' => 'what', 'bar' => 'foo'] // or JSON $container->toJSON(); // -> {"foo": "what", "bar": "foo"} // JSON via JsonSerializable $json = json_encode($container); // -> {"foo": "what", "bar": "foo"} //non-existing properties will be ignored: $container->nope = 'what'; var_dump($container->nope); // -> null
高级用法
// from library 1 trait SomeOptions{ protected string $foo; protected string $what; // this method will be called in SettingsContainerAbstract::construct() // after the properties have been set protected function SomeOptions():void{ // just some constructor stuff... $this->foo = strtoupper($this->foo); } /* * special prefixed magic setters & getters */ // this method will be called from __set() when property $what is set protected function set_what(string $value):void{ $this->what = md5($value); } // this method is called on __get() for the property $what protected function get_what():string{ return 'hash: '.$this->what; } } // from library 2 trait MoreOptions{ protected string $bar = 'whatever'; // provide default values }
$commonOptions = [ // SomeOptions 'foo' => 'whatever', // MoreOptions 'bar' => 'nothing', ]; // now plug the several library options together to a single object $container = new class ($commonOptions) extends SettingsContainerAbstract{ use SomeOptions, MoreOptions; }; var_dump($container->foo); // -> WHATEVER (constructor ran strtoupper on the value) var_dump($container->bar); // -> nothing $container->what = 'some value'; var_dump($container->what); // -> hash: 5946210c9e93ae37891dfe96c3e39614 (custom getter added "hash: ")
API
SettingsContainerAbstract
免责声明
这可能是一个绝妙的想法,也可能是一个完全愚蠢的想法 - 由你决定。然而,我喜欢它并且它有效。此外,这不是一个依赖注入容器。请停止使用DI容器。