sagittariusx/beluga.dynamic-properties

帮助类使用通过 get*() 和 set*() 方法声明的动态属性

0.1.0 2016-08-06 18:16 UTC

This package is not auto-updated.

Last update: 2024-09-14 19:47:32 UTC


README

这是一个PHP7的实现,用于简化生成PHP类的一些“魔法”额外功能。

如果您从 \Beluga\DynamicProperties 的类扩展,那么它将添加具有读或读写访问的动态类实例属性。这只需要存在一些 get*() 和/或 set*() 方法。

安装

通过以下方式安装

composer require sagittariusx/beluga.dynamic-properties

或者在 composer.json 内部

   "require": {
      "php": ">=7.0",
      "sagittariusx/beluga.dynamic-properties": "^0.1.0"
   },

用法

用法非常简单。

为什么我应该使用动态属性?

您不应该使用它,但如果您看到优势,您可以使用它。

大多数现代IDE,如 PHPStormNetbeans,如果属性具有正确的PHP-Doc标签注解,则支持使用代码补全功能的动态属性。

这意味着,例如,如果您提供一个名为 $foo 的动态只读属性,类型为 string

/**
 * …
 *
 * @property-read string $foo Description of the property…
 */

对于读写访问,您只需将 @property-read 替换为 @property

动态属性读访问

如果您有一个类,它定义了获取一些实例属性的方法,并且它们的名称格式类似于 getPropertyName1()getPropertyName2() 等。您只需从 \Beluga\DynamicProperties\ExplicitGetter 类扩展该类,并且可以直接访问属性,如 $myClassInstance->propertyName1$myClassInstance->propertyName2 以进行读访问。

类将始终按以前的方式工作,但具有额外的属性。

# include \dirname( __DIR__ ) . '/vendor/autoload.php';

use Beluga\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' ];
   }

}

请记住,不要忘记为动态可用的只读属性编写所需的类文档,如下面的示例 doc-block 。

动态属性读写访问

如果您还需要对属性进行写入访问,您必须将 Beluga\DynamicProperties\ExplicitGetter 替换为 Beluga\DynamicProperties\ExplicitGetterSetter 类,并实现所需的 set???() 方法

#include \dirname( __DIR__ ) . '/vendor/autoload.php';


use Beluga\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;
   }

}

特殊情况:忽略获取器和/或设置器

通常,不是所有 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' ];

   }