niirrty / niirrty.dynprop
动态PHP类属性库。
0.6.2
2024-03-11 08:54 UTC
Requires
- php: >=8.1
Requires (Dev)
- phpunit/phpunit: 9.*
README
这是PHP8的一个实现,可以轻松地为你的PHP类生成一些“魔法”额外功能。
安装
在 composer.json
内部
{ "require": { "php": ">=8.1", "niirrty/niirrty.dynprop": "~0.6" } }
使用
使用非常简单。
为什么我应该使用动态属性?
你不应该使用它,但如果你看到它的优点,你可以使用。
大多数现代IDE,如 PHPStorm 或 Netbeans,如果属性具有正确的PHP-Doc标签注释,则支持动态属性以及代码补全功能。
例如,如果你提供一个名为 $foo
的类型为 string
的动态只读属性
/** * … * * @property-read string $foo Description of the property… */
对于读写访问,你只需将 @property-read
替换为 @property
。
动态属性读取访问
如果你有一个类定义了获取一些实例属性的方法,并且它们的名称格式像 getPropertyName1()
或 getPropertyName2()
等。你只需从 \UK\DynProp\ExplicitGetter
类扩展类,并且可以直接访问属性,如 $myClassInstance->propertyName1
或 $myClassInstance->propertyName2
以进行读取访问。
类将始终像以前一样工作,但具有额外的属性。
# include \dirname( __DIR__ ) . '/vendor/autoload.php'; use Niirrty\DynProp\ExplicitGetter; /** * @property-read string $foo … * @property-read bool $bar … */ class MyClass extends ExplicitGetter { private $properties = [ 'foo' => 'foo', 'bar' => true ]; public function getFoo() : string { return $this->properties[ 'foo' ]; } public function getBar() : bool { return $this->properties[ 'bar' ]; } }
请记住,不要忘记为动态可用的只读属性编写所需的类文档,如下面的示例 doc-block 中所示。
动态属性读写访问
如果你还需要对属性进行写访问,你必须将 Niirrty\DynProp\ExplicitGetter
替换为 Niirrty\DynProp\ExplicitGetterSetter
类,并实现所需的 set???() 方法
#include \dirname( __DIR__ ) . '/vendor/autoload.php'; use Niirrty\DynProp\ExplicitGetterSetter; /** * @property string $foo … * @property-read bool $bar … */ class MyClass extends ExplicitGetterSetter { private $properties = [ 'foo' => 'foo', 'bar' => true ]; public function getFoo() : string { return $this->properties[ 'foo' ]; } public function getBar() : bool { return $this->properties[ 'bar' ]; } public function setFoo( string $value ) : MyClass { if ( \strlen( $value ) < 1 ) { throw new \LogicException( 'Foo can not use an empty string' ); } $this->properties[ 'foo' ] = $value; return $this; } }
特殊情况:忽略获取器和/或设置器
通常不是所有 get* 和/或 set* 方法都应作为动态属性使用。
对于这些情况,你可以明确声明不应通过动态方式访问的属性的名称。
为此,你必须在扩展类的构造函数中定义这些动态属性名称
public function __construct() { // ignore the getBar() method $this->ignoreGetProperties = [ 'bar' ]; // If the class extends from ExplicitGetterSetter you can also // Define the setters that should be ignored. e.g.: ignore setFoo() $this->ignoreSetProperties = [ 'foo' ]; }