grottopress/setter

直接设置私有对象属性,无需调用setter方法。

v1.0.0 2023-05-31 20:32 UTC

This package is auto-updated.

Last update: 2024-09-23 15:30:54 UTC


README

描述

Setter 允许您直接设置 私有 对象属性,而无需调用setter方法。

例如,您可以直接使用 $myObject->myAttr = $newValue,而不是调用 $myObject->setMyAttr($newValue)。在内部,Setter 通过调用您在类中定义的私有方法 setMyAttr() 来设置属性。

这样,您既获得了语法糖的好处,又保持了封装性。

安装

使用composer安装

composer require grottopress/setter

用法

将特性导入到您的类中,并这样使用

<?php
declare (strict_types = 1);

namespace Vendor;

use GrottoPress\Setter\SetterTrait;

class MyClass {
    /**
     * Import trait
     */
    use SetterTrait;

    private $changeMe;
    private $leaveMeAlone;

    /**
     * Define your private setter method
     * Method name should be of the format "set{$attrName}"
     */
    private function setChangeMe($newValue)
    {
        $this->changeMe = $newValue;
    }

    // ...
}

// Instantiate
$object = new Vendor\MyClass();

// Try to set attributes
$object->changeMe = 'New Me!'; // => Works!
$object->leaveMeAlone = 'xyz'; // => Error: 'setLeaveMeAlone()' not defined

开发

使用 composer run test 运行测试。

贡献

  1. 分支它
  2. 切换到 master 分支: git checkout master
  3. 创建您的功能分支: git checkout -b my-new-feature
  4. 进行更改,并根据需要更新更改日志和文档。
  5. 提交更改: git commit
  6. 推送到分支: git push origin my-new-feature
  7. GrottoPress:master 分支提交新的 Pull Request