Package Data | |
---|---|
Maintainer Username: | rkgrep |
Maintainer Contact: | 1@grep.su (Roman Kinyakin) |
Package Create Date: | 2015-05-08 |
Package Last Update: | 2015-06-27 |
Language: | PHP |
License: | MIT |
Last Refreshed: | 2024-11-19 03:09:19 |
Package Statistics | |
---|---|
Total Downloads: | 36 |
Monthly Downloads: | 1 |
Daily Downloads: | 0 |
Total Stars: | 3 |
Total Watchers: | 1 |
Total Forks: | 0 |
Total Open Issues: | 0 |
Note: Original idea by Taylor Otwell in Laravel Framework.
The package includes traits which allow fluent and elegant way to work with internal object property arrays.
Install the package with composer.
composer require rkgrep/attributable
Apply the trait to any class you need.
class Foo {
use rkgrep\Attributable;
}
class Bar {
use rkgrep\Fillable;
}
Attributable
provides different access and assignment ways.
Assign internal variables via property or method call
$foo->var1 = 1;
$foo->var2(2);
Access variables via property
echo $foo->var1;
echo $foo->var2;
Provide fallback value via get
method
$foo->get('var4', 'fallback');
$foo->get('var5', function() { return 'closure result'; });
Get all internal variables via getAttributes
method
$all = $foo->getAttributes();
Method call without arguments assigns true
$foo->viewable();
true == $foo->viewable;
Chain methods for fast assignment
$user->first_name('John')->last_name('Doe')->admin();
Fillable
provides chaining assignment of variables or groups of variables.
Mass assign atributes with fill
method
$user->fill(['name' => 'Admin', 'email' => 'admin@example.com']);
Overwrite or reassign control via second parameter
$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
$user->with('password', md5('password'));
Prevent overriding with third parameter
$user->with('password', '', false); // Password remains untouched
Assign multiple variables
$user->with(['friends' => ['Mike', 'Dave'], 'girlfriend' => 'Jane']);
$user->with(['siblings' => [], 'girlfriend' => 'Mary'], null, false); // Overriding disabled - only siblings are touched
Chain method calls
$post->fill(['title' => 'Lorem Ipsum'])->with('views', 5)->with('likes', 3);
Any class with Attributable
trait applied implements ArrayAccess
and JsonSerializable
.
If you use illuminate/support package you can also apply Arrayable
and Jsonable
interfaces.
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 package is open-sourced package licensed under the MIT license.