alexanevsky/getter-setter-accessor-bundle

提供从对象读取和写入的功能,并获取对象获取器和设置器的列表。

1.0.3 2024-08-25 22:34 UTC

This package is auto-updated.

Last update: 2024-09-25 22:53:30 UTC


README

此库提供从对象读取和写入的功能,并获取对象获取器和设置器的列表。

目录

  1. 第一步
  2. 获取值
  3. 设置值
  4. 获取获取器列表
  5. 获取获取器列表

第一步

GetterSetterAccessor 添加到控制器或服务的构造函数中

use Alexanevsky\GetterSetterAccessorBundle\GetterSetterAccessor;

public function __construct(
    private GetterSetterAccessor $getterSetterAccessor
) {}

然后让我们获取一些对象(例如,某些模型)的访问器

$objectAccessor = $this->getterSetterAccessor->createAccessor($objectAccessor);

获取值

我们可以使用 getValue() 方法获取任何属性的值,例如

echo $objectAccessor->getValue('userName');
echo $objectAccessor->getValue('user_name');

属性名称可以是驼峰式或蛇形。它将被转换为实际使用的名称。

如果对象没有获取器,将抛出异常。在使用 getValue() 之前,我们可以使用 hasGetter() 方法确保获取器存在

if ($objectAccessor->hasGetter('userName')) {
    echo $objectAccessor->getValue('userName');
}

设置值

我们可以使用 setValue() 方法设置任何属性的值,例如

echo $objectAccessor->SetValue('userName', 'John Doe');
echo $objectAccessor->SetValue('user_name', 'John Doe');

属性名称可以是驼峰式或蛇形。它将被转换为实际使用的名称。

如果对象没有设置器,将抛出异常。在使用 setValue() 之前,我们可以使用 hasSetter() 方法确保设置器存在

if ($objectAccessor->hasSetter('userName')) {
    echo $objectAccessor->setValue('userName', 'John Doe');
}

获取获取器列表

我们可以使用 getGetters() 方法获取所有可用的对象获取器列表。结果,我们将得到一个 ObjectGetter[] 数组,其中每个对象都有以下方法

  • getValue() - 返回一个值
  • getName() - 返回属性名称
  • isNullable() - 检查值是否允许为 null
  • getTypes() - 返回值可以具有的类型列表
  • getAttribute(attributeClass) - 通过其类名返回属性实例
  • getAttribute(attributeClass) - 通过其类名检查属性是否存在

获取获取器列表

我们可以使用 getGetters() 方法获取所有可用的对象获取器列表。结果,我们将得到一个 ObjectGetter[] 数组,其中每个对象都有以下方法

  • getValue() - 返回一个值
  • getName() - 返回属性名称
  • isNullable() - 检查值是否允许为 null
  • getTypes() - 返回值可以具有的类型列表
  • getAttribute(attributeClass) - 通过其类名返回属性实例
  • getAttribute(attributeClass) - 通过其类名检查属性是否存在

祝你好运!