2016-02-01 95 views
1

我創建了一個名爲Router導入所有控制器這樣的類:匹配控制器名稱,並調用特定的功能

<?php 

include dirname(dirname(__FILE__)) . '\application\controllers\backend.php'; 

class Router 
{ 
    private $_backend; 

    public function __construct() 
    { 
     $this->_backend = new Backend(); 
    } 

    /** 
    * Execute function 
    */ 

    public function submit($controller, $func) 
    { 
     // $this->_backend->index(); 
    } 
} 

?> 

現在這個班是我router.php文件中提供,該文件在其他人之前包括,我可以通過引用訪問到路由器類的任何PHP文件:

$router = new Router(); 

我的任務是可調用的函數index在進口backend控制器210文件。在index.php文件我有:

$router->submit('backend', 'index'); 

如何我可以匹配控制器名稱,並調用作爲參數傳遞與變量的函數我Router類裏面?

回答

1
<?php 
class Router 
{ 
    public function submit($controller, $func) 
    { 
     // include dynamically the needed file 
     include dirname(dirname(__FILE__)) . '\application\controllers\' . $controller . '.php'; 
     // The classname starts with capital 
     $Class = ucfirst($controller); 
     // create an instance 
     $ctr = new $Class(); 
     // and call the requested function 
     $ctr->$func(); 
    } 
} 
+0

所以我不能在路由器類的頂部導入所有的控制器,並根據傳遞的參數調用特定的控制器? – Dillinger

+0

你可以把它們全部放在頂部,然後從我的代碼中移除包含行 – Gavriel