aesonus / php-magic
读取类注释以确定魔术方法的行为
0.4.3
2020-07-29 05:07 UTC
Requires
- php: ^7.2
- aesonus/parse-use-statements: ^1.1
- jan-swiecki/simple-annotations: 0.3.1
Requires (Dev)
- aesonus/test-lib: v3.0
README
读取类注释以验证并使用 __get、__set、__isset 和 __unset 获取、设置、检查或取消设置定义的不可访问对象属性。
安装
使用 composer 安装
composer require aesonus/php-magic
用法
基本用例
- 将 trait 导入您的类
class MyClass { use HasMagicProperties; // or use HasInheritedMagicProperties; }
- 使用 phpdoc 格式的注释添加属性到注释块中,并定义同名对象属性
use \stdClass; /** * Yup, the question mark can be used to indicate null * @property ?string $testStringOrNullProperty Optional description * The | can validate using 'or' * @property float|string $testFloatOrStringProperty * @property-read int $testIntReadProperty * @property-read callable|object $testCallableOrObjectReadProperty * @property-write stdClass|null $testStdClassOrNullWriteProperty * @property-write mixed $testMixedWriteProperty */ class MyClass { use HasMagicProperties; protected $testStringOrNullProperty; protected $testFloatOrStringProperty; protected $testIntReadProperty; protected $testCallableOrObjectReadProperty; protected $testStdClassOrNullWriteProperty; protected $testMixedWriteProperty; ... }
- 创建魔术方法,并使它们调用相应的 magic[Get|Isset|Set|Unset] 方法(提示:如果您不需要实现所有魔术方法,则不需要实现所有魔术方法)
在这个例子中,我们自行设置了魔术属性方法
/** * ... */ class MyClass { use HasMagicProperties; /** * Only readable properties will be read (@property or @property-read) */ public function __get($name) { return $this->magicGet($name); } /** * Only readable properties will be read (@property or @property-read) */ public function __isset($name) { return $this->magicIsset($name); } /** * Only writable properties will be set (@property or @property-write) */ public function __set($name, $value) { $this->magicSet($name, $value); } /** * Only writeable properties will be set (@property or @property-write) */ public function __unset($name) { $this->magicUnset($name); } ... }
您也可以使用 ImplementsMagicMethods trait 自动实现所有魔术函数
/** * ... */ class MyClass { use HasMagicProperties; use ImplementsMagicMethods; ... }
- 您也可以在魔术方法中定义自定义行为,如果需要的话
/** * ... */ class MyClass { public function __get($name) { // Do something return $this->magicGet($name); } public function __set($name, $value) { $this->magicSet($name, $value); //Manipulate the set value after the validation, if wanted } ... }
类型验证
trait 将使用在注释块中定义的类型来验证输入。它目前支持任何可以通过 is_int、is_bool 等调用的类型;以及您可能需要的任何类。
以下示例验证参数为 My\Namespace\Foo 或 My\Other\Namespace\Bar 类
use My\Namespace\Foo; use My\Other\Namspace\Bar; /** * * @property $myClass Foo|Bar */ class MyClass { }