rkgrep / attributable
Fast an elegant way to make dynamic objects
Requires
- php: >=5.4.0
Requires (Dev)
- phpunit/phpunit: ~4.0
This package is auto-updated.
Last update: 2024-12-18 19:10:57 UTC
README
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.
Installation
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; }
Usage
Attributable trait
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 trait
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);
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.
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.