dtoq41429 2012-11-19 12:22
浏览 17
已采纳

带MVC的PHP前端控制器

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

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

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

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

}

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?

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.

  • 写回答

3条回答 默认 最新

  • dqys98341 2012-11-19 16:07
    关注

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

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度