設計模式 - 在php項目中 各位兄台是怎麼優雅的調用工具類庫的呢?

來源:互聯網
上載者:User
最近一直在糾結 項目分層架構的問題 其中最糾結的就是在項目中 如何引入第三方類庫

比如說 有個 msg控制器 要發送郵件

class MsgConstroller extends Constroller {    public function send() {       $email = new email([options....]);       $email->send();    }}

這個控制器通過引入一個 email 工具類 實現了發送 email 的功能 但是如果同時要傳送簡訊呢

class MsgConstroller extends Constroller {        public function send() {           $email = new email([options....]);           $sms = new sms([options....]);           $email->send();           $sms->send();        }    }

這樣感覺很不優雅 所以 我想到了使用個服務層來解決

class MsgConstroller extends Constroller {        public function send() {          $msg = service('Msg');  //執行個體化一個Msg服務類           $msg->send('message,email,sms'); //通過send介面傳的參數 會同時發送站內信、郵件、簡訊        }    }

但是 這樣 又會把 new 操作給轉移到服務層 感覺還不是怎麼理想 那麼 大家有什麼比較 簡單優雅的解決方案嗎?

回複內容:

最近一直在糾結 項目分層架構的問題 其中最糾結的就是在項目中 如何引入第三方類庫

比如說 有個 msg控制器 要發送郵件

class MsgConstroller extends Constroller {    public function send() {       $email = new email([options....]);       $email->send();    }}

這個控制器通過引入一個 email 工具類 實現了發送 email 的功能 但是如果同時要傳送簡訊呢

class MsgConstroller extends Constroller {        public function send() {           $email = new email([options....]);           $sms = new sms([options....]);           $email->send();           $sms->send();        }    }

這樣感覺很不優雅 所以 我想到了使用個服務層來解決

class MsgConstroller extends Constroller {        public function send() {          $msg = service('Msg');  //執行個體化一個Msg服務類           $msg->send('message,email,sms'); //通過send介面傳的參數 會同時發送站內信、郵件、簡訊        }    }

但是 這樣 又會把 new 操作給轉移到服務層 感覺還不是怎麼理想 那麼 大家有什麼比較 簡單優雅的解決方案嗎?

你的做法已經可以了。再最佳化可以再包裹一個有依賴注入的訊息類,郵件簡訊各種類全變成私人變數,操作方法裡傳入參數控制是否執行個體化並賦值給私人變數,send方法支援連綴,用起來類似於

$message = new Message();$result = $message->send(array('mail', 'mail_address'))->send(array('sms', 'tel'));

再切設計模式也是萬變不離其宗,又想用著爽又想升級改動的時候好維護是沒有出路的。封裝粒度太粗好用難改;太細好改難用。

再一個,別什麼都跟優雅扯上關係,就兩行程式而已哪那麼多優雅。

sms和email等同時實現send()方法介面,再用Composite設計模式組合起來怎樣?

class MsgConstroller extends Constroller {    public function send() {      $msg = new MsgComposite();      $msg->add(new email());      $msg->add(new sms());      $msg->send();    }}

new操作現在架構好像都喜歡用統一的ServiceLocator解決,方便統一替換利於單元測試

類似這種需求更合適 Service ,在 Symfony2 中可以使用服務,只需配置好服務可以在全域任何地方調用:

$mailer = $this->get('mailer');

同理:

$sms = $this->get('sms');

參考:

http://symfony.com/doc/current/book/service_container.html

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.