phputil/traits

Useful traits for PHP

1.3 2017-01-05 01:21 UTC

This package is auto-updated.

Last update: 2024-12-23 04:13:30 UTC


README

Useful traits for PHP.

Build Status

We use semantic version. See our releases.

Installation

composer require phputil/traits

Traits

Examples

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 )