PHP中流畅的界面设计模式实例

55 阅读1分钟

流利的界面设计模式用于定义类的方法/属性,使其易于阅读/遵循,就像自然语言中的普通句子。

class Traveller
{
    private $who;
    private $from;
    private $time;
    private $day;
    private $month;
    private $year;
    private $by;
    private $to;

    public function setWho(string $who): self
    {
        $this->who = $who;

        return $this;
    }

    public function setFrom(string $from): self
    {
        $this->from = $from;

        return $this;
    }

    public function setTime(string $time): self
    {
        $this->time = $time;

        return $this;
    }

    public function setDay(string $day): self
    {
        $this->day = $day;

        return $this;
    }

    public function setMonth(string $month): self
    {
        $this->month = $month;

        return $this;
    }

    public function setYear(int $year): self
    {
        $this->year = $year;

        return $this;
    }

    public function setBy(string $by): self
    {
        $this->by = $by;

        return $this;
    }

    public function setTo(string $to): self
    {
        $this->to = $to;

        return $this;
    }

    // We are actually not interested in this method but adding for printing purposes
    public function __toString(): string
    {
        return sprintf(
            '%s will travel from %s to %s at %s on %s in %s %d by %s.',
            $this->who,
            $this->from,
            $this->to,
            $this->time,
            $this->day,
            $this->month,
            $this->year,
            $this->by
        );
    }
}

方法

$traveller = new Traveller();
$traveller
    ->setWho('Inanzzz')
    ->setFrom('London')
    ->setTo('Liverpool')
    ->setTime('11:00')
    ->setDay('Monday')
    ->setMonth('January')
    ->setYear(2019)
    ->setBy('train');

echo $traveller->__toString();
echo PHP_EOL;

结果

$ php index.php 
Inanzzz will travel from London to Liverpool at 11:00 on Monday in January 2019 by train.