快速入门开发
执行流程
在开发之前,我们先看执行下面这个url的执行过程:
www.example.com/index.php
没错,首先会执行index.php,初始化define常量,然后调用执行core/CodeIgniter.php:
1、加载config文件、core目录下一些文件
require_once(BASEPATH.'core/compat/mbstring.php');
require_once(BASEPATH.'core/compat/hash.php');
require_once(BASEPATH.'core/compat/password.php');
require_once(BASEPATH.'core/compat/standard.php');
2、加载核心router.php类
$RTR =& load_class('Router', 'core', isset($routing) ? $routing : NULL);
3、查找并加载controller类
$route['default_controller'] = 'welcome';//默认controleer类
require_once(APPPATH.'controllers/'.$RTR->directory.$class.'.php');
4、执行controler类方法,并输出
//application/controllers/Welcome.php
public function index()
{
$this->load->view('welcome_message');
$this->load->dbforge();
}
controller开发
www.example.com/index.php/Test/Myfunc
www.example.com/Test/Myfunc
www.example.com/index.php?c=Test&m=Myfunc
以上3个url都是一样的效果,最后都是执行application/controllers/Test.php里面的Test类的Myfunc方法:
//application/controllers/Test.php
class Test extends CI_Controller {
public function index()
{
$this->load->view('welcome_message');
$this->load->dbforge();
}
}
那么问题来了,controller开发时直接新建文件,那么view和model呢?是怎么从controller执行调用view和model呢?
答案是在controller类里面先手动加载,然后再调用。不管是view模块、model模块、数据库访问、类库统统都是通过在controller里面load进来。
//application/controllers/Test.php
class Test extends CI_Controller {
public function index()
{
$this->load->view('welcome_message');//加载view,直接输出welcome_message.php内容
$this->load->model('MTest');//加载MTest(必须继承CI_Model)
$this->MTest->func();//调用
$this->load->library('calendar');//加载类库
echo $this->calendar->generate();//使用
$this->load->database();//todo
}
}
总结
CI框架核心不复杂,只有index.php入口,主要把握controller类,在controller类load相关模块然后实现逻辑。