The Clean Architecture in PHP 讀書筆記(二)

本文為系列文章的第二篇,第一篇地址是

The Clean Architecture in PHP 讀書筆記(一)

你的解耦工具

在下面的文章中,主要會圍繞去耦給出5大工具,讓你輕松去耦。

  • Design Patterns,A Primer
  • SOLID Design Principles
  • Depedency Injection
  • Defining a Contract with Interfaces
  • Abstracting with Adapters

先介紹第一個(gè)工具:設(shè)計(jì)模式。

Design Patterns,A Primer

設(shè)計(jì)模式是對軟件中通用問題的總結(jié),有了設(shè)計(jì)模式,方便我們進(jìn)行交流,譬如一說MVC,我們就知道是怎么回事了,不然我們必須巴拉巴拉一大堆話去描述,不易于傳播、交流,一個(gè)好的設(shè)計(jì)模式必然有一個(gè)簡單易懂的名字,因?yàn)橹挥泻唵蔚臇|西,才能被大家廣泛傳播。

如今,一談到設(shè)計(jì)模式,被大家廣泛傳播的就是1994年四人幫提出的23種模式,分為了3大類別:

  1. Creational
  2. Structural
  3. Behavioral

本書不會去按個(gè)介紹23個(gè)模式,這樣去介紹的書籍太多了,而且本書也沒有那么多篇幅去按個(gè)講,但是這些都是再進(jìn)行展開的基礎(chǔ),因此我們會介紹一些最近本的概念:

  1. Factory:負(fù)責(zé)生產(chǎn)對象,類似于語言本省提供的new關(guān)鍵字,在C++中與new的不同就在于,new不能通過string直接實(shí)例化對象,但是factory可以
  2. Repository:不是GoF中提出的設(shè)計(jì)模式,其類似于一個(gè)倉庫,負(fù)責(zé)數(shù)據(jù)的存儲和獲取
  3. Adapter:適配器,故名思議就是將接口實(shí)現(xiàn)轉(zhuǎn)換
  4. Strategy:目的是靈活性,將一個(gè)或一組行為封裝起來,方便的進(jìn)行替換

對上面的概念具體展開

The Factory Patterns

簡單代碼:

$customer = new Customer();

如果customer足夠簡單,上面的創(chuàng)建沒有問題,但是如果customer創(chuàng)建的時(shí)候,必須進(jìn)行一堆初始化,那我們就瘋了,一個(gè)簡單的想法,當(dāng)然是將這些創(chuàng)建邏輯抽離出來,變?yōu)橐粋€(gè)函數(shù),進(jìn)行復(fù)用,因此就有下面的版本,

復(fù)雜代碼:


class CustomerFactory {
    protected $accountManagerRepo;

    public function __construct(AccountManagerRepository $repo) { 
        $this->accountManagerRepo = $repo;
    }

    public function createCustomer($name) { 
        $customer = new Customer(); 
        $customer->setName($name); 
        $customer->setCreditLimit(0); 
        $customer->setStatus('pending'); 
        $customer->setAccountManager(
          $this->accountManagerRepo->getRandom()
        );
        return $customer; 
    }
}

總結(jié)下出現(xiàn)上面代碼的原因:軟件復(fù)雜度的提升,可以這么說,軟件中各種問題的出現(xiàn),都是因?yàn)檐浖膹?fù)雜度,不同的復(fù)雜度有不同的應(yīng)對方法,總的目標(biāo)都是為了降低復(fù)雜度

那上面出現(xiàn)的CustomerFactory帶來的好處是:

  1. Reusable code.創(chuàng)建的地方都可以調(diào)用這段代碼,降低了代碼的復(fù)雜度。
  2. Testable code.由于關(guān)注點(diǎn)分離了,方便測試,可以單獨(dú)進(jìn)行創(chuàng)建邏輯的測試
  3. Easy to change.創(chuàng)建邏輯只在一處,方便修改
Static Factories
class CustomerFactory {
    public static function createCustomer($name) {
        $customer = new Customer(); 
        $customer->setName($name); 
        $customer->setCreditLimit(0); 
        $customer->setStatus('pending');
        return $customer; 
    }
}
$customer = CustomerFactory::createCustomer('ACME Corp');

靜態(tài)工廠,通過一個(gè)static方法訪問,那怎么評判是靜態(tài)工廠好,還是上面一個(gè)工廠好呢?答案是:

It depends

沒有最好的,只有更合適的,如果靜態(tài)方法能滿足需求,那就是用靜態(tài)工廠,如果你是數(shù)據(jù)源會經(jīng)常變化,那就使用實(shí)例化工廠,并且將需要的依賴注入進(jìn)來。

Types of Factories
  1. The Factory Method pattern:定義了創(chuàng)建對象的方法,但是具體創(chuàng)建哪個(gè)對象,由子類決定
  2. The Abstract Factory pattern:抽象工廠模式的粒度更粗一點(diǎn),不僅管一個(gè)對象的創(chuàng)建,而是管著一組相關(guān)對象的創(chuàng)建

talk is cheap,show me the code

讓我們上代碼的。

class Document {

    public function createPage() {

        return new Page();
    }

}

如果我們又好幾種page,怎么辦?

class Document {

    public function createPage($type) {
      switch $type {
        case "ResumeDocument":
          return new ResumePage();
        case "PortfolioDocument":
          return new PortfolioPage();
      }
    }

}

上面代碼的問題是:我們每次新曾一個(gè)類型的page,必須要修改createPage方法,不滿足開放封閉原則(OCP),那PHP有個(gè)好處是,直接傳遞給new字符串就能創(chuàng)建對象,看代碼:

class Document {

    public function createPage($type) {
      return new $type;
    }
}

問題:我們無法驗(yàn)證傳入$type的有效性,而且對createPage返回的類型,我們也無法檢查,那怎么辦呢?

思路是:將創(chuàng)建邏輯按照關(guān)注點(diǎn)分離的邏輯,每個(gè)類型的document創(chuàng)建自己的page,這就解決了$type的有效性問題,那對于返回值,我們定義一個(gè)公共接口,只有實(shí)現(xiàn)這個(gè)接口的才是符合預(yù)期的。

abstract class AbstractDocument {
    abstract public function createPage():PageInterface;
}
class ResumeDocument extends AbstractDocument {         
  public function createPage():PageInterface {
        return new ResumePage(); 
    }
}
class PortfolioDocument extends AbstractDocument {      
  public function createPage():PageInterface {
        return new PortfolioPage(); 
    }
}
interface PageInterface {}
class ResumePage implements PageInterface {} 
class PortfolioPage implements PageInterface {}

介紹第一個(gè)概念The Abstract Factory pattern

抽象工廠就是對于工廠方法的1+1=2的疊加。

如果我們的Document不止創(chuàng)建一個(gè)page,還要?jiǎng)?chuàng)建cover,那就會有兩個(gè)create方法,此時(shí)每個(gè)子類就多實(shí)現(xiàn)一個(gè)方法的。

Repository Pattern

倉儲模式:該模式在Eric Evan的神書:Domain-Driven Design: Tackling Complexity in the Heart of Software中詳細(xì)的進(jìn)行了描述

A REPOSITORY represents all objects of a certain type as a conceptual set (usuallyemulated). It acts like a collection, except with more elaborate querying capability.

Domain-Driven Design, Eric Evans, p. 151

倉儲類似于一個(gè)數(shù)據(jù)集合,相比較集合有更多精細(xì)設(shè)計(jì)的query,當(dāng)我們談?wù)揜epository的時(shí)候,我們關(guān)注的不再是“querying the database”,而是更純粹的目的:存取數(shù)據(jù)

常用的讀取數(shù)據(jù)的方法


class MyRepository {
    public function getById($id); 
    public function findById($id); 
    public function find($id); 
    public function retrieve($id);
}

常用的寫方法:

class MyRepository {
    public function persist($object); 
    public function save($object);
}

每個(gè)Repository對應(yīng)一個(gè)類的存取,有多個(gè)類,就會有多個(gè)Repository。

一個(gè)Repository怎么工作?

Objects of the appropriate type are added and removed, and the machinery behindthe REPOSITORY inserts them or deletes them from the database.

Domain-Driven Design, Eric Evans, p. 151

主要給出一些資源:

Dotrine ORM:實(shí)現(xiàn)了Date Mapper

Eloquent ORM,Propel:實(shí)現(xiàn)了Active Record

Zend Framework 2:提供了Table Data Gateway模式

如果你想要自己實(shí)現(xiàn)一個(gè)Repository,強(qiáng)烈推薦Patterns of Enterprise Application Architecture

關(guān)于數(shù)據(jù)庫的各種模式,推薦一個(gè)ppt

Adapter Pattern

直接看代碼:

class GoogleMapsApi {
    public function getWalkingDirections($from, $to) {}
}
interface DistanceInterface {
    public function getDistance($from, $to);
}
class WalkingDistance implements DistanceInterface {    
  public function getDistance($from, $to) {
        $api = new GoogleMapsApi();
        $directions = $api->getWalkingDirections($from, $to);
        return $directions->getTotalDistance(); 
    }
}

適配器,非常明確的表名了意圖,通過WalkingDistance將GoogleMapsApi適配為了DistanceInterface

Strategy Pattern

也是看代碼:

public function invoiceCustomers(array $customers) { 
    foreach ($customers as $customer) {
        $invoice = $this->invoiceFactory->create(
          $customer,
          $this->orderRepository->getByCustomer($customer)
        );
        // send invoice...
    } 
}
// 此處我們根據(jù)用倉庫里獲取到的用戶賬單,通知用戶


interface InvoiceDeliveryInterface { 
  public function send(Invoice $invoice);
}

class EmailDeliveryStrategy implements InvoiceDeliveryInterface { 
    public function send(Invoice $invoice) {
    // Use an email library to send it
    } 
}
class PrintDeliveryStrategy implements InvoiceDeliveryInterface { 
    public function send(Invoice $invoice) {
    // Send it to the printer
    } 
}
// 賬單有兩種通知方式,一種是發(fā)郵件,一種是print

public function invoiceCustomers(array $customers) { 
    foreach ($customers as $customer) {
        $invoice = $this->invoiceFactory->create(
        $customer,
        $this->orderRepository->getByCustomer($customer));
    switch ($customer->getDeliveryMethod()) { 
    case 'email':
        $strategy = new EmailDeliveryStrategy();
        break; 
    case 'print': 
    default:
        $strategy = new PrintDeliveryStrategy();
        break; 
    }
    $strategy->send($invoice);
  }
}
// 通過策略模式:我們可以在runtime,根據(jù)不同的賬單,選擇而不同的發(fā)送策略
// 問題:發(fā)送策略的選擇不應(yīng)該在外部直接暴露,改選擇什么通知策略,應(yīng)該是用戶自己知道的,因此就有了下面的代碼:

class InvoiceDeliveryStrategyFactory {
    public function create(Customer $customer) {
        switch ($customer->getDeliveryMethod()) { 
        case 'email':
            return new EmailDeliveryStrategy();
            break; 
        case 'print': 
        default:
            return new PrintDeliveryStrategy();
            break; 
        }
    } 
}
// 此時(shí)的客戶端,根據(jù)最少職責(zé)原則,此時(shí)invoiceCustomers值負(fù)責(zé)創(chuàng)建賬單,并且發(fā)送,并不負(fù)責(zé)選擇什么方式寄送
public function invoiceCustomers(array $customers) {    
  foreach ($customers as $customer) {
    $invoice = $this->invoiceFactory->create(
      $customer,
      $this->orderRepository->getByCustomer($customer));
    $strategy = $this->deliveryMethodFactory->create(
      $customer);
    $strategy->send($invoice);
  }
}

更多的設(shè)計(jì)模式:

  1. 設(shè)計(jì)模式:可復(fù)用面向?qū)ο筌浖幕A(chǔ)
  2. Head First Design Patterns

請期待下一篇SOLID Design Principles

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,991評論 19 139
  • ?? 對設(shè)計(jì)模式的極簡說明!?? 這個(gè)話題可以輕易讓任何人糊涂。現(xiàn)在我嘗試通過用 最簡單 的方式說明它們,來讓你(和我...
    月球人simon閱讀 1,127評論 1 2
  • 文章作者:Tyan博客:noahsnail.com 3.4 Dependencies A typical ente...
    SnailTyan閱讀 4,206評論 2 7
  • 1 人和動(dòng)物情同此理 這幾年,老媽在臨汾,兒子在長治,這兩個(gè)地方去得就多了點(diǎn)。去得多了,有時(shí)候,在公交車上打個(gè)盹,...
    聽風(fēng)閣主人閱讀 351評論 3 2
  • “我想跟你說:你不要舍不得我,因?yàn)槲乙采岵坏媚恪?阿風(fēng)知道自己心里住著一個(gè)惡魔,每隔一段時(shí)間就會浮現(xiàn)出來。 秀走的...
    浪子峰閱讀 272評論 1 0