PHP架構開發:四、控制器(Controller)的實現

來源:互聯網
上載者:User

上一節中對MVC設計模式進行了簡單說明,本節我們來實現MVC的C--Controller。

  • 在application/controller檔案夾中建立一個PHP檔案,取名為HomeController.php,並添加如下代碼:
  • <?php class HomeController{     function indexAction()     {     }}?>

這幾行代碼告訴我們要實現的控制器的結構,即:控制器檔案(及類)的名字是以控制器名+後輟Controller組成的;控制器含有方法indexAction,這個方法名是由動作名+後輟Action組成的。

如第二節中所說的,我們希望通過這樣的URL: http://www.example.com/home/index 來訪問到這個控制器(其實就是找到這個檔案)。

下面來修改Rewrite.php檔案以達到存取控制器的目的:

  • 修改library/LQP/Rewrite.php檔案,添加一個dispatch方法,修改後檔案內容如下:
  • <?php/** * Description of Rewrite * * @author z */class LQP_Rewrite{    protected            $_urlPath,            $_controllerName,            $_actionName;    private function  __construct() {        $this->_urlPath = $_SERVER['REQUEST_URI'];        $params = explode('/', $this->_urlPath);        if($params)            $this->_controllerName = empty($params[1])?'home':$params[1];        if(count($params) > 1)            $this->_actionName = empty ($params[2])?'index':$params[2];    }    /**     * 執行相應控制器中的相應動作     */    function dispatch()    {        $controllerClassName = ucfirst($this->_controllerName)."Controller";        $controllerFile = APP_CONTROLLER_DIR."/$controllerClassName.php";
    require_once $controllerFile;//載入控制器檔案 $controller = new $controllerClassName();//建立一個控制器的對象
    $action = $this->_actionName; $action .= "Action"; $controller->$action();//調用控制器中相應的動作(方法) }}

    主要代碼已加了注釋,應該不難理解了


    • 為了使dispatch方法生效,及方便日後載入其它檔案內容,我們建立一個library/LQP/Loader.php檔案,內容如下:
    • <?phprequire_once 'Rewrite.php';$rewrite = new LQP_Rewrite();$rewrite->dispatch();?>
      • 讓客戶程式載入Loader.php,在public/config/lib_config.php中加入一行:
      • require_once 'Loader.php';

      經過上面的步驟,我們訪問http://www.example.com/home/index時就會去執行indexAction方法了,當然如果訪問http://www.example.com/home/register,架構程式就會去自動執行registerAction方法,此時我們只要在HomeController中加入一個名為registerAction的方法就可以了。

      不管是indexAction,還是registerAction,根據MVC的思想都不應該直接來顯示內容,顯示內容是由V(View)來提供的,所以下一節我們將介紹本架構中視圖(View)的實現。

      總節:本節只是簡單介紹的Controller,為的讓你輕鬆的理解其原理,為了讓架構更具有可用性,後續的章節中會逐漸加深、完善Controller。

       

       

      本節源碼:http://cid-8248e4adbf2b92f3.office.live.com/self.aspx/.Public/Lesson%204.rar

      聯繫我們

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