PHP開發模式之代理技術

來源:互聯網
上載者:User

標籤:cal   sse   執行個體   containe   x11   ram   自己   常用   soap   

在實際開發中,我們經常要調用第三方的類庫如SOAP服務等。使用這些第三方 組件並不難,最麻煩的莫過於調用了,一般的調試手段最方便的莫過於記日誌了。 樣本: 假如有以下第三方類庫。

// filename: user.phpclass user{    // 得到使用者資訊    public function getInfo($uid){      }}

  

一般的程式員寫的調用代碼可能是: include ‘user.php‘; $face = new user(); $uid = 100; // 參數寫日誌 $info = $face->getInfo($uid); // 返回的結果再寫日誌 這裡有個問題,如果要用到第三方介面很多,則這種方式將是一個惡夢的開始; 這裡我採用一種Proxy代理方式,在 Ruby 語言中有一個非常專業 的名詞AOP可以形容這種技術,即動態為類增強方法。

// 代理技術class VProxy{      // 單例,如果在複雜資源時比較有用,如SOAP/DB等    static private $_instance = array();          /**     * 單例模式返回實現(推薦)     *     * @param string $model 介面模型名     * @return object     */    static public function getInstance($model)    {        $model = strtolower($model);        if(!isset(self::$_instance[$model])){            self::$_instance[$model] = new self($model);        }        return self::$_instance[$model];    }      /**     * 當前調用介面的執行個體     *     * @var unknown_type     */    private $_model = null;    private $_modelName = ‘‘;      /**     * 建構函式     *     * @param string $model 介面模型名     */    public function __construct($model){        include_once($model.‘.php‘);        $this->_modelName = $model;        $this->_model = new $model;    }      /**     * proxy核心方法     *     * @param string $functionName :方法名     * @param mixed $args :傳給方法的參數     * @return unknown     */    public function __call($functionName,$args)    {        // 調用介面        $result = call_user_func_array(array($this->_model, $functionName), $args));        // 寫日誌        writeLog($this->_modelName,$functionName,$args,$result);        // 返回結果        return $result;    }}  // 調用執行個體$face = VProxy::getInstance(‘user‘);$info = $face->getInfo(100);

  

該執行個體子只是起個畫龍點睛而以,具體實現應用比這種複雜,利用以上技術還可以為介面增加相關的方法, 這點就類似Javascript中對象的特性了,具體自己嘗試下吧!我在迅雷具體項目中經常用到該技術, 比如說為部門提供公用服務介面等。

 

轉自:http://www.vquickphp.com/?a=blogview&id=25

PHP開發模式之代理技術

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.