PHP 代码简洁之道(小结)(13)

优秀的:

abstract class Shape
{
  abstract public function getArea(): int;

  public function render(int $area): void
  {
    // ...
  }
}

class Rectangle extends Shape
{
  private $width;
  private $height;

  public function __construct(int $width, int $height)
  {
    $this->width = $width;
    $this->height = $height;
  }

  public function getArea(): int
  {
    return $this->width * $this->height;
  }
}

class Square extends Shape
{
  private $length;

  public function __construct(int $length)
  {
    $this->length = $length;
  }

  public function getArea(): int
  {
    return pow($this->length, 2);
  }
}

/**
 * @param Rectangle[] $rectangles
 */
function renderLargeRectangles(array $rectangles): void
{
  foreach ($rectangles as $rectangle) {
    $area = $rectangle->getArea(); 
    $rectangle->render($area);
  }
}

$shapes = [new Rectangle(4, 5), new Rectangle(4, 5), new Square(5)];
renderLargeRectangles($shapes);

接口隔离原则 (ISP)

ISP 指出 "客户不应该被强制依赖于他们用不到的接口."

一个好的例子来观察证实此原则的是针对需要大量设置对象的类,不要求客户端设置大量的选项是有益的,因为多数情况下他们不需要所有的设置。使他们可选来避免产生一个 “臃肿的接口”.

坏的:

interface Employee
{
 public function work(): void;

 public function eat(): void;
}

class Human implements Employee
{
 public function work(): void
 {
  // ....working
 }

 public function eat(): void
 {
  // ...... eating in lunch break
 }
}

class Robot implements Employee
{
 public function work(): void
 {
  //.... working much more
 }

 public function eat(): void
 {
  //.... robot can't eat, but it must implement this method
 }
}

好的:

并不是每个工人都是雇员,但每个雇员都是工人.

interface Workable
{
 public function work(): void;
}

interface Feedable
{
 public function eat(): void;
}

interface Employee extends Feedable, Workable
{
}

class Human implements Employee
{
 public function work(): void
 {
  // ....working
 }

 public function eat(): void
 {
  //.... eating in lunch break
 }
}

// robot can only work
class Robot implements Workable
{
 public function work(): void
 {
  // ....working
 }
}

依赖反转原则 (DIP)

这一原则规定了两项基本内容:

高级模块不应依赖于低级模块。两者都应该依赖于抽象.
抽象类不应依赖于实例。实例应该依赖于抽象.
一开始可能很难去理解,但是你如果工作中使用过 php 框架(如 Symfony), 你应该见过以依赖的形式执行这一原则
依赖注入 (DI). 虽然他们不是相同的概念,DIP 可以让高级模块不需要了解其低级模块的详细信息而安装它们.