okeyaki/preset

此包已被废弃且不再维护。没有建议的替代包。

提供方便的特性以实现数据类。

1.1.1 2016-05-07 17:36 UTC

This package is not auto-updated.

Last update: 2017-09-26 16:12:45 UTC


README

Preset 提供方便的特性以实现数据类。

要求

  • PHP >= 5.5.9

安装

composer require okeyaki/preset

使用方法

Preset\Immutable

Preset\Immutable 提供不可变类的通用实现。

它支持

  • 构造器
  • 属性访问
  • 相等比较
  • 继承

构造器

class Point2D
{
    use Preset\Immutable;

    private $x;

    private $y;
}

new Point2D([
    'x' => 0,
    'y' => 1,
]);

如果需要,您可以覆盖构造器。

class Point2D
{
    use Preset\Immutable;

    private $x;

    private $y;

    public function __construct($x, $y)
    {
        $this->x = $x;
        $this->y = $y;
    }
}

new Point2D(0, 1);

属性访问

class Point2D
{
    use Preset\Immutable;

    private $x;

    private $y;
}

$p = new Point2D([
    'x' => 0,
    'y' => 1,
]);

$p->x; // 0
$p->y; // 1

您可以定义获取器来钩子操作。

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

相等比较

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

如果想要通过标识符比较对象,请覆盖 Preset\Immutable::equals()

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

继承

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 扩展 Preset\Immutable 并提供可变类的通用实现。

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