PHP架構開發第一步--原廠模式

來源:互聯網
上載者:User
幾乎所有的PHP架構都使用單入口檔案方式,也就是說所有的請求都是從index.php進入。那就必須要用到原廠模式來實現請求的分發。

例如,我們在請求這樣的URL :

http://www.test.com/index.php?c=User&a=index



含義是我們需要請求User控制器的index方法。也就是說index.php需要根據參數去建立User控制器的執行個體,並調用index方法。它好像就是實現了一個“工廠”的功能。

我們可以這樣實現一個工廠類:

class Factory{public static function getInstance($controller_name,$action_name){if(class_exists($controller_name)){$controller = new $controller_name;if(method_exists($controller,$action_name)){$controller->$action_name();}else{exit('action not found');}}else{exit('controller not found');}}}



有了這個工廠類,我們在index.php中只需要編寫下面的代碼,就可以完成全部的邏輯了:

$controller_name = $_GET['c'];$action_name = $_GET['a'];Factory::getInstance($controller_name,$action_name);



分析一下上面的代碼,首先接收到控制器名稱和方法名稱,傳遞給工廠類Factory的getInstance方法。Factory會自動幫我們執行個體化控制器,並調用相應的方法。

這就是工廠類,給他一定的參數,它能幫你做剩下的工作。

再來看看工廠類是怎麼實現的。它首先會檢查控制器類是否存在:

class_exists($controller_name);



如果類不存在,會提示:controller not found.

然後會建立控制器的執行個體,再檢查方法是否存在並執行。

method_exists($controller,$action_name);



這就是工廠類的實現原理,當然還可以繼續完善它。

在更多的情況下,我們會把控制器放在獨立的檔案中,這時候工廠類需要先引入控制器檔案:

require('app/controller/'.$controller_name.'.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.