dbx12/base-object

可配置对象,受Yii2框架启发。

v1.0.1 2021-11-22 09:16 UTC

This package is auto-updated.

Last update: 2024-09-22 15:21:16 UTC


README

Build

这个库深受Yii2框架中可配置对象的启发。

安装

与任何composer库一样

composer require dbx12/base-object

概念

基本对象允许您使用配置数组设置类的属性。默认情况下,只能通过这种方式设置公共和受保护的属性。如果您想设置私有属性,请为其定义一个setter。setter的模式是set + 属性名,例如对于属性$name -> function setName($value)。getter的命名方式类似(以相同示例:function getName())。

如果您通过公共setter和getter公开私有或受保护的属性,可以通过在您的类上添加@property-read@property-write注解来帮助您的IDE。如果您有一个getter和一个setter,可以将它们合并为@property。对于上述示例(没有setter),您将编写@property-write string $name

用法

默认(无setter)

class MyObject extends \dbx12\baseObject\BaseObject {
    public $publicVariable;
    protected $protectedVariable;
    private $privateVariable;
}

// this will fail with an UnknownPropertyException because setting $privateVariable is not allowed
$instance = new MyObject([
    'publicVariable' => 'publicValue',
    'protectedVariable' => 'protectedValue',
    'privateVariable' => 'privateValue',
]);

使用受保护的setter

class MyObject extends \dbx12\baseObject\BaseObject {
    public $publicVariable;
    protected $protectedVariable;
    private $privateVariable;
    
    protected function setPrivateVariable($value): void
    {
        $this->privateVariable = $value;
    }
}

// this will succeed
$instance = new MyObject([
    'publicVariable' => 'publicValue',
    'protectedVariable' => 'protectedValue',
    'privateVariable' => 'privateValue',
]);

// and this will produce an error as the setter is not visible from the global scope
$myObject->setPrivateVariable('bar');

没有公共getter

class MyObject extends \dbx12\baseObject\BaseObject {
    public $publicVariable;
    protected $protectedVariable;
    private $privateVariable;

    protected function setPrivateVariable($value): void
    {
        $this->privateVariable = $value;
    }
}

$myObject = new MyObject([
    'publicVariable' => 'publicValue',
    'protectedVariable' => 'protectedValue',
    'privateVariable' => 'privateValue',
]);

// this will throw an UnknownPropertyException
echo $myObject->protectedVariable;

使用公共getter

/**
 * @property-read $protectedVariable
 */
class MyObject extends \dbx12\baseObject\BaseObject {
    public $publicVariable;
    protected $protectedVariable;
    private $privateVariable;

    protected function setPrivateVariable($value): void
    {
        $this->privateVariable = $value;
    }

    public function getProtectedVariable()
    {
        return $this->protectedVariable;
    }
}

$myObject = new MyObject([
    'publicVariable' => 'publicValue',
    'protectedVariable' => 'protectedValue',
    'privateVariable' => 'privateValue',
]);

// this will succeed
echo $myObject->getProtectedVariable();

// this will succeed and your IDE will show you a hint for it thanks to the @property-read annotation
echo $myObject->protectedVariable;