okeyaki / preset
This package is abandoned and no longer maintained.
No replacement package was suggested.
Provides conviniece traits to implement data classes.
1.1.1
2016-05-07 17:36 UTC
Requires
- php: >=5.5.9
Requires (Dev)
- phpunit/phpunit: ~4.8
This package is not auto-updated.
Last update: 2017-09-26 16:12:45 UTC
README
Preset provides conviniece traits to implement data classes.
Requirements
- PHP >= 5.5.9
Installation
composer require okeyaki/preset
Usage
Preset\Immutable
Preset\Immutable provides generic implementation for immutable classes.
It supports:
- Constructor
- Property Access
- Equality Comparison
- Inheritance
Constructor
class Point2D { use Preset\Immutable; private $x; private $y; } new Point2D([ 'x' => 0, 'y' => 1, ]);
You can override the constructor if needed.
class Point2D { use Preset\Immutable; private $x; private $y; public function __construct($x, $y) { $this->x = $x; $this->y = $y; } } new Point2D(0, 1);
Property Access
class Point2D { use Preset\Immutable; private $x; private $y; } $p = new Point2D([ 'x' => 0, 'y' => 1, ]); $p->x; // 0 $p->y; // 1
You can define getters to hook the actions.
class Point2D { use Preset\Immutable; private $x; private $y; public function x() { return $this->x + 1; } } $p = new Point2D([ 'x' => 0, 'y' => 1, ]); $p->x; // 1 $p->y; // 1
Equality Comparison
class Point2D { use Preset\Immutable; private $x; private $y; } $first = new Point2D([ 'x' => 0, 'y' => 1, ]); $second = new Point2D([ 'x' => 0, 'y' => 1, ]); $third = new Point2D([ 'x' => 1, 'y' => 1, ]); $first->equals($second); // true $first->equals($third); // false
Override Preset\Immutable::equals()
if you want to compare objects with their identifiers.
class Point2D { use Preset\Immutable; private $id; private $x; private $y; public function equals($rhs) { return $this->id === $rhs->id; } } $first = new Point([ 'id' => 1, 'x' => 0, 'y' => 1, ]); $second = new Point([ 'id' => 2, 'x' => 0, 'y' => 1, ]); $third = new Point([ 'id' => 1, 'x' => 1, 'y' => 1, ]); $first->equals($second); // false $first->equals($third); // true
Inheritance
You should declare properties of a sub-class as **protected**.
class Point2D { use Preset\Immutable; private $x; private $y; } class Point3D extends Point2D { protected $z; } $p = new Point2D([ 'x' => 0, 'y' => 1, 'z' => 2, ]); $p->x; // 0 $p->y; // 1 $p->z; // 2
Preset\Mutable
Preset\Mutable extends Preset\Immutable and provides generic implementation for mutable classes.
class Point2D { use Preset\Mutable; private $x; private $y; } $p = new Point2D([ 'x' => 0, 'y' => 1, ]); $p->x = 1; $p->y = 2; $p->x; // 1 $p->y; // 2