aesonus/php-magic

读取类注释以确定魔术方法的行为

0.4.3 2020-07-29 05:07 UTC

This package is auto-updated.

Last update: 2024-09-29 04:37:17 UTC


README

Build Status

读取类注释以验证并使用 __get、__set、__isset 和 __unset 获取、设置、检查或取消设置定义的不可访问对象属性。

安装

使用 composer 安装

composer require aesonus/php-magic

用法

基本用例

  1. 将 trait 导入您的类
class MyClass {
    use HasMagicProperties;
    // or
    use HasInheritedMagicProperties;
}
  1. 使用 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;
    ...
}
  1. 创建魔术方法,并使它们调用相应的 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;
    ...
}
  1. 您也可以在魔术方法中定义自定义行为,如果需要的话
/**
 * ...
 */
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 {

}