带有MVC的PHP前端控制器 [英] PHP Front Controller with MVC

查看:100
本文介绍了带有MVC的PHP前端控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用前端控制器设计研究MVC.

I am trying to delve into MVC with Front Controller Design.

我想用一行来调用我的整个应用程序,例如在index.php中:

I want to invoke my entire application by using one line, for example in index.php:

require_once(myclass.php);
$output = new myClass();

我很想摆脱require_once行,但是我不知道如何在不包含类的情况下加载我的课程?

I would love to get rid of the require_once line, but I don't see how I could load my class without including it?

无论如何,我的主要问题是如何使用一个前端类加载各种控制器,模型和视图等.到目前为止,我已经想到了:

Anyway my main question would be how to load my various controllers and models and views etc using a one front end class. So far I have come up with:

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");
        }
    }

}

但是似乎有点令人费解,并且超过了顶部.另外,一旦我将新类包含在__construct中,我应该如何加载它?

But it seems a bit convoluted and over the top. Also, once i've included the new class in the __construct, How am I supposed to load it?

很抱歉,我缺乏知识,我已经在Google上搜索了很多次,而且我不断提出相同的页面,但这些页面似乎并没有扩大我对此事的了解.

Im sorry for the lack of knowledge, I have googled this a number of times and I keep coming up with the same pages that don't seem to expand my knowledge on the matter.

推荐答案

令我惊讶的是,在这两个冗长而翔实的先前答案中,没有人愿意以最简单的方式实际回答您的问题.

I'm surprised that in those two long and informative previous answers nobody bothered to actually answer your question in the simplest way.

您需要 __autoload() 函数.您仍然必须在代码中的某个位置定义它,但是可以将其简单地添加到全局头文件中,然后不必为每个类定义显式编写一个include.

You want the __autoload() function. You'll still have to define it somewhere in your code, but it can simply be added to a global header file and then you don't have to explicitly write an include for every class definition.

/* auto load model classes */
function __autoload($class_name) {
        $filename = 'class.' . strtolower($class_name) . '.php';
        $file = __SITE_PATH . '/_model/' . $filename;
        if( file_exists($file) == false ) {
                return false;
        }
        require($file);
}

这篇关于带有MVC的PHP前端控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆