Useful traits for PHP.
We use semantic version. See our releases.
composer require phputil/traits
Example on GetterBuilder
:
use phputil\traits\GetterBuilder;
class MyClass {
use GetterBuilder; // simulate getters
private $name = '';
private $description = '';
function __construct( $name, $description ) {
$this->name = $name;
$this->description = $description;
}
}
$obj = new MyClass( 'Bob', 'I am Bob' );
echo $obj->getName(); // Bob
echo $obj->getDescription(); // I am Bob
Example on WithBuilder
:
use phputil\traits\WithBuilder;
class MyClass {
use WithBuilder;
public $name = '';
public $description = '';
}
$obj = ( new MyClass() )->withName( 'Bob' )->withDescription( 'I am Bob' );
echo $obj->name; // Bob
echo $obj->description; // I am Bob
Example on GetterSetterWithBuilder
:
use phputil\traits\GetterSetterWithBuilder;
class MyClass {
use GetterSetterWithBuilder;
private $name = '';
private $description = '';
}
$obj = ( new MyClass() )->withName( 'Bob' )->setDescription( 'I am Bob' );
echo $obj->getName(); // Bob
echo $obj->getDescription(); // I am Bob
$obj->setName( 'Bob Dylan' );
echo $obj->getName(); // Bob Dylan
Example on FromArray
:
use phputil\traits\FromArray;
class MyClass {
use FromArray;
private $id;
protected $name;
public $age;
}
$obj = new MyClass();
$obj->fromArray( array( 'id' => 10, 'name' => 'Bob', 'age' => 18 ) );
var_dump( $obj ); // the attributes will have the array values
Example on converting from a dynamic object:
// From a converting from a dynamic object, just use a type casting
$p = new \stdClass;
$p->id = 10;
$p->name = 'Bob';
$p->age = 18;
$obj = new MyClass();
$obj->fromArray( (array) $p ); // Just make a type casting to array ;)
Example on ToArray
:
use phputil\traits\ToArray;
class MyClass {
use ToArray;
private $id = 50;
protected $name = 'Bob';
public $age = 21;
}
$obj = new MyClass();
var_dump( $obj->toArray() ); // array( 'id' => 50, 'name' => 'Bob', 'age' => 21 )