Attributable
, (*1)
Note: Original idea by Taylor Otwell in Laravel Framework., (*2)
The package includes traits which allow fluent and elegant way to work with internal object property arrays., (*3)
Installation
Install the package with composer., (*4)
composer require rkgrep/attributable
Apply the trait to any class you need., (*5)
class Foo {
use rkgrep\Attributable;
}
class Bar {
use rkgrep\Fillable;
}
Usage
Attributable trait
Attributable provides different access and assignment ways., (*6)
Assign internal variables via property or method call, (*7)
$foo->var1 = 1;
$foo->var2(2);
Access variables via property, (*8)
echo $foo->var1;
echo $foo->var2;
Provide fallback value via get method, (*9)
$foo->get('var4', 'fallback');
$foo->get('var5', function() { return 'closure result'; });
Get all internal variables via getAttributes method, (*10)
$all = $foo->getAttributes();
Method call without arguments assigns true, (*11)
$foo->viewable();
true == $foo->viewable;
Chain methods for fast assignment, (*12)
$user->first_name('John')->last_name('Doe')->admin();
Fillable trait
Fillable provides chaining assignment of variables or groups of variables., (*13)
Mass assign atributes with fill method, (*14)
$user->fill(['name' => 'Admin', 'email' => 'admin@example.com']);
Overwrite or reassign control via second parameter, (*15)
$user->fill(['name' => 'John Doe']); // Name changed, email remains untouched
$user->fill(['email' => 'other@example.com'], false); // Disabled merging - old values are dropped
Fill specific properties with with method, (*16)
$user->with('password', md5('password'));
Prevent overriding with third parameter, (*17)
$user->with('password', '', false); // Password remains untouched
Assign multiple variables, (*18)
$user->with(['friends' => ['Mike', 'Dave'], 'girlfriend' => 'Jane']);
$user->with(['siblings' => [], 'girlfriend' => 'Mary'], null, false); // Overriding disabled - only siblings are touched
Chain method calls, (*19)
$post->fill(['title' => 'Lorem Ipsum'])->with('views', 5)->with('likes', 3);
Interfaces
Any class with Attributable trait applied implements ArrayAccess and JsonSerializable.
If you use illuminate/support package you can also apply Arrayable and Jsonable interfaces., (*20)
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();
License
Attributable package is open-sourced package licensed under the MIT license., (*21)