PHP MVC 框架架构建议


PHP MVC Framework Architecture Advice

我已经程序化编写了好几年了,最近我决定跳到面向对象的代码。

为了帮助我站稳脚跟,我一直在开发自己的MVC框架。我知道Zend等等,但我只是想要一些优雅和轻量级的东西,在那里我100%理解一切,并且可以积累知识。但是,我需要一点帮助和建议。

基本文件夹体系结构为:

/view/
/controller/
/model/
index
.htaccess

这些是我到目前为止拥有的文件:

/.htaccess

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z]*)/?(.*)?$ index.php?controller=$1&path=$2 [NC,L]

/索引.php

//autoload new classes
function __autoload($class) 
{
    $folder = explode('_', $class);
    require_once strtolower(str_replace('_', '/', $class)).'_'.$folder[0].'.php';
}
//instantiate controller
if (!isset($_GET['controller'])) { $_GET['controller'] = 'landing'; }
$controller_name = 'controller_'.$_GET['controller'];
new $controller_name($_GET,$_POST); 
/

控制器/base_controller.php

abstract class controller_base
{   
    //store headers
    protected $get;
    protected $post;
    //store layers
    protected $view;
    protected $model;
    protected function __construct($get,$post)
    {    
        //store the header arrays
        $this->get = $get;
        $this->post = $post;
        //preset the view layer as an array
        $this->view = array();
    }
    public function __destruct()
    {
        //extract variables from the view layer
        extract($this->view);
        //render the view to the user
        require_once('view/'.$this->get['controller'].'_view.php');
    }
}
/

控制器/landing_controller.php

class controller_landing extends controller_base
{
    public function __construct($get,$post)
    {
        parent::__construct($get,$post);
        //simple test of passing some variables to the view layer     
        $this->view['text1']  = 'some different ';
        $this->view['text2']  = 'bit of text'; 
    }
}

问题1)这个框架的布局是否正确?

问题2)我应该如何将模型层集成到这个框架中?

问题3)关于如何改善这一点的任何其他建议?

好吧,我会尽力回答最好的,我可以。

对问题 1 的回答

嗯,这是主观的。如果这是您想要的工作方式,那么是的!我所做的不同之处在于,在我的htaccess中,我只是将"http://domain.com/"之后的EVERYTING作为参数传递给get参数,然后在PHP中处理数据。例如像这样:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php?urlparam=$1 [NC,L,QSA]

然后在 PHP 中处理它:

$_GET['urlparam'];
# Do whatever here. Maybe explode by "/".

最后一件事是路由部分。我只是制作与URL匹配的模式。

例如/ads/:id

导致''广告''显示

对问题 2 的回答

当我需要将视图、模型、插件或任何其他文件加载到我的控制器中时,我正在运行一个加载类,我称之为加载类。这样我就可以确定,该文件只加载一次。load-model 函数只是返回一个带有模型的对象,这样我就实例化了它,以后可以使用它。

对问题 3 的回答

您可能应该阅读一些教程。我认为,Anant Garg在本教程中很好地解释了它:http://anantgarg.com/2009/03/13/write-your-own-php-mvc-framework-part-1/

但是有很多"在那里"

例如这个:http://www.phpro.org/tutorials/Model-View-Controller-MVC.html

或者这个给出了 12 种不同的方法:http://www.ma-no.org/en/content/index_12-tutorials-for-creating-php5-mvc-framework_1267.php

希望这对您朝着正确的方向有所帮助,

祝您晚上愉快。:)