第一課中搭建的基本的 框架模型, 只有一個 index.php 做爲執行文件,按這種方式最不穩定的因素就是路徑的問題。php
咱們常常須要經過合適的參數,好比 load_class('output') 或 $this->load->libraray('email') 等函數就能夠加載到相應的類,因此本課將回歸到 CI 整個目錄體系結構,以 system 和 application ,從新對代碼進行組織。app
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 文件夾中ui
全部 core 代碼 include 時必須加上 BASEPATHthis
3. 將 models, views, controllers 文件夾移動到 application 目錄下,將 routes.php 移動到 application/config 目錄下url
修改 Loader.php 中構造函數中路徑的設置,以及 Router 函數中 include routes.php 的路徑,分別以下spa
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 徹底一致,以下圖所示:code