Chu*_*d37 2 php model-view-controller front-controller
我正在尝试使用Front Controller Design深入研究MVC.
我想通过使用一行来调用我的整个应用程序,例如在index.php中:
require_once(myclass.php);
$output = new myClass();
Run Code Online (Sandbox Code Playgroud)
我很想摆脱require_once线,但我不知道如何加载我的课程而不包括它?
无论如何,我的主要问题是如何使用一个前端类加载我的各种控制器和模型和视图等.到目前为止,我想出了:
class myClass
{
private $name;
public $root = $_SERVER['DOCUMENT_ROOT'];
private $route = array("Controller" => "", "Model" => "", "View" => "", "Paremeters" => "");
function __construct()
{ $uri = explode("/",$_SERVER['REQUEST_URI']);
if(isset($uri[2])) {$this->route['Controller'] = $uri[2];}
if(isset($uri[3])) {$this->route['Model'] = $uri[3];}
if(isset($uri[4])) {$this->route['View'] = $uri[4];}
if(isset($this->route['Controller']))
{
include($this->root."/".$this->route['Controller'].".php");
}
}
}
Run Code Online (Sandbox Code Playgroud)
但它看起来有点令人费解并超过顶部.此外,一旦我在__construct中包含了新类,我该如何加载它?
我很抱歉缺乏知识,我已经多次用Google搜索,我不断提出相同的页面似乎并没有扩展我对这个问题的了解.
如果您的网址肯定是http://domain.com/[controller]/[action]/ 参数,那么您的前端控制器可能如下所示:
<?php
class Application
{
public function __construct()
{
$this->setupAutoloader();
$this->route();
}
private function setupAutoloader()
{
// do your autoloading here
}
private function route()
{
$request = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
$controller = isset($request[0]) ? ucwords(array_shift($request)) . 'Controller' : 'HomeController';
$action = isset($request[0]) ? array_shift($request) : 'index';
$parameters = $request;
$response = call_user_func_array(array($controller, $action), $parameters);
}
}
Run Code Online (Sandbox Code Playgroud)
从这里,您可以添加自动加载器实现,对响应执行任何操作,并从index.php中调用它,如下所示:
<?php
require 'path/to/Application.php';
$application = new Application();
Run Code Online (Sandbox Code Playgroud)
不幸的是,如果它存储在文件系统的其他位置,你总是必须包含第一个文件,但是如上所述,你可以自动加载其他类,如库,控制器,模型等.