一步一步重写 CodeIgniter 框架 (12) —— 代码再重构,回归 CI

第一课中搭建的基本的 框架模型, 只有一个 index.php 作为执行文件,按这种方式最不稳定的因素就是路径的问题。

我们经常需要通过合适的参数,比如 load_class('output') 或 $this->load->libraray('email') 等函数就可以加载到相应的类,所以本课将回归到 CI 整个目录体系结构,以 system 和 application ,重新对代码进行组织。

 

1. 对 index.php 进行重新组织,定义基本的常量,并分离出核心的 CodeIgniter 类

<?php
/**
 * 框架主入口文件,所有的页面请求均定为到该页面,并根据 url 地址来确定调用合适的方法并显示输出
 */

define('ENVIRONMENT', 'development');


if (defined('ENVIRONMENT')) {
    switch (ENVIRONMENT) {
        case 'development':
            error_reporting(E_ALL);
            break;

        case 'testing':
        case 'production':
            error_reporting(0);

        default:
            exit('The application environment is not set correctly');
            break;
    }
}

$system_path = 'system';

$application_folder = 'application';

if (defined('STDIN')) {
    chdir(dirname(__FILE__));
}

if (realpath($system_path) !== FALSE) {
    $system_path = realpath($system_path). '/';
}

// 确保 system_path 有一个 '/'
$system_path = rtrim($system_path, '/').'/';

if ( ! is_dir($system_path)) {
    exit("Your system folder path does not appear to be set correctly. Please open the following file and correct this: ".pathinfo(__FILE__, PATHINFO_BASENAME));
}


define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));

define('EXT', '.php');

define('BASEPATH', str_replace("\\", "/", $system_path));

define('FCPATH', str_replace(SELF, '', __FILE__));

// Name of the "system folder"
define('SYSDIR', trim(strrchr(trim(BASEPATH, '/'), '/'), '/'));

if (is_dir($application_folder)) {
    define('APPPATH', $application_folder.'/');
} else {
    if ( ! is_dir(BASEPATH.$application_folder.'/')) {
        exit("Your application folder path does not appear to be set correctly. Please open the following file and correct this: ".SELF);
    }
    define('APPPATH', BASEPATH.$application_folder.'/');
}

require_once BASEPATH.'core/CodeIgniter.php';

注意,我们只是对当前代码按照 CI 的组织结构进行重构,在 index.php 文件中进行 route 和 config 的设置将在以后课程中完善。

 

2.  将 core 代码移动到 system 文件夹中

  所有 core 代码 include 时必须加上 BASEPATH

3. 将 models, views, controllers 文件夹移动到 application 目录下,将 routes.php 移动到 application/config 目录下

  修改 Loader.php 中构造函数中路径的设置,以及 Router 函数中 include routes.php 的路径,分别如下

function __construct() {
        $this->_ci_ob_level = ob_get_level();

        $this->_ci_library_paths = array(APPPATH, BASEPATH);
        $this->_ci_helper_paths = array(APPPATH, BASEPATH);
        $this->_ci_model_paths = array(APPPATH);
        $this->_ci_view_paths = array(APPPATH.'views/' => TRUE);
}
if (is_file(APPPATH.'config/routes.php')) {
            include(APPPATH.'config/routes.php');
}

 

最后,整个目录体系将与 CI 完全一致,如下图所示:

posted @ 2013-08-28 10:27  风影无忌  阅读(5518)  评论(1编辑  收藏  举报