rkgrep/attributable

快速优雅地创建动态对象的方法

v1.1 2015-05-14 05:49 UTC

This package is auto-updated.

Last update: 2024-09-18 18:28:32 UTC


README

Build Status Latest Stable Version Latest Unstable Version License SensioLabsInsight

注意:原始想法来自Taylor Otwell在Laravel框架

该包包含特性,允许流畅优雅地处理内部对象属性数组。

安装

使用composer安装此包。

composer require rkgrep/attributable

将特性应用于您需要的任何类。

class Foo {
    
    use rkgrep\Attributable;
    
}
class Bar {
    
    use rkgrep\Fillable;
    
}

使用方法

Attributable特性

Attributable提供了不同的访问和赋值方式。

通过属性或方法调用赋值内部变量

$foo->var1 = 1;
$foo->var2(2);

通过属性访问变量

echo $foo->var1;
echo $foo->var2;

通过get方法提供回退值

$foo->get('var4', 'fallback');
$foo->get('var5', function() { return 'closure result'; });

通过getAttributes方法获取所有内部变量

$all = $foo->getAttributes();

不带参数的方法调用赋值为true

$foo->viewable();
true == $foo->viewable;

链式方法进行快速赋值

$user->first_name('John')->last_name('Doe')->admin();

Fillable特性

Fillable提供变量或变量组的链式赋值。

使用fill方法批量赋值属性

$user->fill(['name' => 'Admin', 'email' => 'admin@example.com']);

通过第二个参数控制覆盖或重新赋值

$user->fill(['name' => 'John Doe']); // Name changed, email remains untouched
$user->fill(['email' => 'other@example.com'], false); // Disabled merging - old values are dropped

使用with方法填充特定属性

$user->with('password', md5('password'));

通过第三个参数防止覆盖

$user->with('password', '', false); // Password remains untouched

赋值多个变量

$user->with(['friends' => ['Mike', 'Dave'], 'girlfriend' => 'Jane']);
$user->with(['siblings' => [], 'girlfriend' => 'Mary'], null, false); // Overriding disabled - only siblings are touched

链式调用方法

$post->fill(['title' => 'Lorem Ipsum'])->with('views', 5)->with('likes', 3);

接口

应用了Attributable特性的任何类都实现了ArrayAccessJsonSerializable接口。如果您使用illuminate/support包,还可以应用ArrayableJsonable接口。

class Bar implements ArrayAccess, JsonSerializable, Arrayable, Jsonable {

    use rkgrep\Attributable;

}

$bar = new Bar();
$bar->value('test');

$arrayValue = $bar['value'];
$bar['value'] = 'new';
$json = json_encode($bar); // returns '{"value": "new"}'

$array = $bar->toArray();
$json = $bar->toJson();

许可证

Attributable包是开源软件,受MIT许可证许可。