skybluesofa/chainable

允许使用链式、流畅的方法调用

v0.1.0 2016-10-03 16:44 UTC

This package is auto-updated.

Last update: 2024-09-20 01:36:52 UTC


README

Build Status Code Climate Test Coverage Total Downloads Version Software License

链式

允许使用链式、流畅的方法调用

链式方法

查看 [Tests/Sandwich(https://github.com/skybluesofa/chainable/blob/master/tests/Sandwich.php)] 类。它展示了链式特质的多种用法。

此特性的基本使用

  • 将链式函数的可见性设置为 'private'
  • 确保您修改当前类或返回类的克隆版本
  • 确保您返回类的引用
private function withBread($breadType=null) {
  $this->breadType = $breadType;
  return $this;
}

调用流畅方法

现在您可以流畅地调用这些方法

Sandwich::withBread('white')->
  addCondiment('peanut butter')->
  addCondiment('jelly')->
  make();

或者相同的三明治,但方法的调用顺序不同

Sandwich::addCondiment('peanut butter')->
  withBread('white')->
  addCondiment('jelly')->
  make();

修改输出

在您返回除链式类引用之外的其他内容之前,您可以修改输出内容

Sandwich::withBread('wheat')->
  addCondiment('peanut butter')->
  addCondiment('grape jelly')->
  withBread('white')->
  removeCondiment('grape jelly')->
  addCondiment('strawberry jelly')->
  make();

缺少的方法

这将抛出异常,因为 'addBananas' 方法不存在。

Sandwich::withBread('white')->
  addCondiment('peanut butter')->
  addBananas()->
  make();

公共方法

这将返回错误,因为 'addVegetable' 方法不是静态的

Sandwich::addVegetable('lettuce')->
  withBread('white')->
  make();

为了解决这个问题,在调用 'addVegetable' 之前使用 'chainableProxy' 方法

Sandwich::chainableProxy()->
  addVegetable('lettuce')->
  withBread('white')->
  make();