项目作者: thiagodp

项目描述 :
🔮 Be more productive with PHP
高级语言: PHP
项目地址: git://github.com/thiagodp/traits.git
创建时间: 2016-08-15T22:26:51Z
项目社区:https://github.com/thiagodp/traits

开源协议:MIT License

下载


phputil\traits

Useful traits for PHP.

Build Status

We use semantic version. See our releases.

Installation

  1. composer require phputil/traits

Traits

Examples

Example on GetterBuilder:

  1. use phputil\traits\GetterBuilder;
  2. class MyClass {
  3. use GetterBuilder; // simulate getters
  4. private $name = '';
  5. private $description = '';
  6. function __construct( $name, $description ) {
  7. $this->name = $name;
  8. $this->description = $description;
  9. }
  10. }
  11. $obj = new MyClass( 'Bob', 'I am Bob' );
  12. echo $obj->getName(); // Bob
  13. echo $obj->getDescription(); // I am Bob

Example on WithBuilder:

  1. use phputil\traits\WithBuilder;
  2. class MyClass {
  3. use WithBuilder;
  4. public $name = '';
  5. public $description = '';
  6. }
  7. $obj = ( new MyClass() )->withName( 'Bob' )->withDescription( 'I am Bob' );
  8. echo $obj->name; // Bob
  9. echo $obj->description; // I am Bob

Example on GetterSetterWithBuilder:

  1. use phputil\traits\GetterSetterWithBuilder;
  2. class MyClass {
  3. use GetterSetterWithBuilder;
  4. private $name = '';
  5. private $description = '';
  6. }
  7. $obj = ( new MyClass() )->withName( 'Bob' )->setDescription( 'I am Bob' );
  8. echo $obj->getName(); // Bob
  9. echo $obj->getDescription(); // I am Bob
  10. $obj->setName( 'Bob Dylan' );
  11. echo $obj->getName(); // Bob Dylan

Example on FromArray:

  1. use phputil\traits\FromArray;
  2. class MyClass {
  3. use FromArray;
  4. private $id;
  5. protected $name;
  6. public $age;
  7. }
  8. $obj = new MyClass();
  9. $obj->fromArray( array( 'id' => 10, 'name' => 'Bob', 'age' => 18 ) );
  10. var_dump( $obj ); // the attributes will have the array values

Example on converting from a dynamic object:

  1. // From a converting from a dynamic object, just use a type casting
  2. $p = new \stdClass;
  3. $p->id = 10;
  4. $p->name = 'Bob';
  5. $p->age = 18;
  6. $obj = new MyClass();
  7. $obj->fromArray( (array) $p ); // Just make a type casting to array ;)

Example on ToArray:

  1. use phputil\traits\ToArray;
  2. class MyClass {
  3. use ToArray;
  4. private $id = 50;
  5. protected $name = 'Bob';
  6. public $age = 21;
  7. }
  8. $obj = new MyClass();
  9. var_dump( $obj->toArray() ); // array( 'id' => 50, 'name' => 'Bob', 'age' => 21 )