uk / dynamic-properties
帮助类使用通过 get*() 和 set*() 方法声明的动态属性
Requires
- php: >=7.0
Requires (Dev)
- phpunit/phpunit: 5.0.*
This package is not auto-updated.
Last update: 2024-09-23 12:20:21 UTC
README
这是一个 PHP7 实现,用于轻松地为你的 PHP 类生成一些“魔法”额外功能。
如果你从 \UK\DynamicProperties 的类之一扩展,它将为具有读写或只读访问权限的动态类实例属性添加功能。它只需要存在一些 get*() 和/或 set*() 方法。
状态
安装
composer require uk/dynamic-properties
使用
使用非常简单。
为什么我应该使用动态属性?
你不应该使用它,但如果你看到它的优点,你也可以使用。
大多数现代 IDE,如 PHPStorm 或 Netbeans,如果属性具有正确的 PHP-Doc 标记,则支持动态属性和代码完成功能。
例如,如果你提供一个名为 $foo 的类型为 string 的动态只读属性
/**
* …
*
* @property-read string $foo Description of the property…
*/
对于读写访问,你只需要将 @property-read 替换为 @property。
动态属性只读访问
如果你有一个类定义了获取某些实例属性的方法,并且它们具有类似于 getPropertyName1() 或 getPropertyName2() 等. 的名称格式,你只需要从 \UK\DynamicProperties\ExplicitGetter 类扩展,并且可以直接访问属性,如 $myClassInstance->propertyName1 或 $myClassInstance->propertyName2 以进行读访问。
该类将始终按原样工作,但具有额外的属性。
# include \dirname( __DIR__ ) . '/vendor/autoload.php'; use UK\DynamicProperties\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' ]; } }
请记住,不要忘记为动态可用的只读属性编写所需的类文档,如下面的示例 docblock 所示。
动态属性读写访问
如果你还需要对属性进行写访问,你必须将 UK\DynamicProperties\ExplicitGetter 替换为 UK\DynamicProperties\ExplicitGetterSetter 类,并实现所需的 set???() 方法
#include \dirname( __DIR__ ) . '/vendor/autoload.php'; use UK\DynamicProperties\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; } }
特殊情况:忽略 Getters 和/或 Setters
通常,并非所有 get* 和/或 set* 方法都应作为动态属性使用。
对于这些情况,你可以明确声明不应通过动态方式访问的属性的名称。
为此,你必须在扩展类的构造函数中定义这些动态属性名称
public function __construct() { // ignore the getBar() method $this->ignoreGetProperties = [ 'bar' ]; // If the class extends from ExplicitGetterSetter you can also // Define the getter that should be ignored. e.g.: ignore setFoo() $this->ignoreSetProperties = [ 'foo' ]; }
文档结束 :-)