PHP& MVC:无法动态创建适当的MVC类

时间:2013-11-25 18:31:11

标签: php dynamic autoload auto-generate

我正在尝试使用MVC模式构建CMS。我的CMS的结构如下:

- > index.php :切入点。包含适当的包含并创建frontController,它将路由器作为参数:

$frontController = new FrontController(new Router);
echo $frontController->output();

- > router.php :分析网址并定义每个模型,视图和控制器的名称。默认情况下,它们以home开头,但如果url的格式为http://localhost/index.php?route=Register,则MVC类将命名为RegisterModel,RegisterView和Register Controller。

if(isset ( $_GET ['route'] ))
{
    $this->URL = explode ( "/", $_GET ['route'] );

    $this->route = $_GET ['route'];
    $this->model = ucfirst($this->URL [0] . "Model");
    $this->view = ucfirst($this->URL [0] . "View");
    $this->controller = ucfirst($this->URL [0] . "Controller");
}
else
{
    $this->model = "HomeModel";
    $this->view = "HomeView";
    $this->controller = "HomeController";
    $this->route = "Home";
}

- > frontController.php :这就是我被困住的地方。当我进入主页时,它可以正确显示,因为我已经创建了默认的HomeModel,HomeView和HomeController类。但是我创建了一个指向注册(localhost/index.php?route=Register)的链接,但是PHP日志表明frontController类没有创建相应的Register类。

class FrontController
{
    private $controller;
    private $view;

    public function __construct(Router $router)
    {
        $modelName = $router->model;
        $controllerName = $router->controller;
        $viewName = $router->view;

        $model = new $modelName ();
        $this->controller = new $controllerName ( $model );
        $this->view = new $viewName ( $router->getRoute(), $model );

        if (! empty ( $_GET['action'] ))
            $this->controller->{$_GET['action']} ();
    }
    public function output()
    {
        // This allows for some consistent layout generation code
        return $this->view->output ();
    }
}

此刻我不知道如何解决这个问题。即使我在frontController中创建了类,有没有办法指定动态生成的类应该从基础Model,View,Controller类扩展?
默认的HomeView.php如下所示:

class HomeView
{
    private $model;
    private $route;
    private $view_file;


    public function __construct($route, HomeModel $model)
    {
        $this->view_file = "View/" . $route . "/template.php";
        echo $this->view_file;
        $this->route = $route;
        $this->model = $model;
    }

    public function output()
    {
        require($this->view_file);
    }
}  

任何可能帮助我摆脱困境或指针朝向正确方向的迹象都将非常感激。

EDIT1:
我忘了添加我的两个问题的摘要:
1.我想了解为什么没有在FrontController类中创建类...
2.一旦创建,我将如何访问这些类?答案在评论部分。使用PHP spl_autoload_register函数。

全部谢谢!

0 个答案:

没有答案