CI4框架应用六 - 控制器应用
这节我们来分析一下控制器的应用,我们看到系统提供的控制器都是继承自一个BaseController,我们来分析一下这个BaseController的作用
1 use CodeIgniter\Controller; 2 3 class BaseController extends Controller 4 { 5 6 /** 7 * An array of helpers to be loaded automatically upon 8 * class instantiation. These helpers will be available 9 * to all other controllers that extend BaseController. 10 * 11 * @var array 12 */ 13 protected $helpers = []; 14 15 /** 16 * Constructor. 17 */ 18 public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger) 19 { 20 // Do Not Edit This Line 21 parent::initController($request, $response, $logger); 22 23 //-------------------------------------------------------------------- 24 // Preload any models, libraries, etc, here. 25 //-------------------------------------------------------------------- 26 // E.g.: 27 // $this->session = \Config\Services::session(); 28 } 29 }
这个控制器的意义就是一个加载组件的场所,把一些常用的组件转成该类的属性,那么其它的控制器继承了这个类也就获得了这些属性,可以在开发中直接使用了,或是预加载一些函数库,在开发中可以直接使用这些函数库里的函数。
我们先来看一下initController这个方法,这个方法的说明是构造器,功能类似于构造方法,但这个只是一个普通的方法,是在类被实例化后手动调用的,这个方法接受三个参数,分别是:
1. $request 请求对象
2. $response 响应对象
3. $logger 日志对象
在构造器方法执行后会转成自身的属性:
1. $this->request
2. $this->response
3. $this->logger
其中 $this->request 特别重要,和用户请求相关的所有信息都可以从这个对象获得
我们看到这个构造器方法还可以加载任何模型,库等等, 例如:
1 /** 2 * Constructor. 3 */ 4 public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger) 5 { 6 // Do Not Edit This Line 7 parent::initController($request, $response, $logger); 8 9 //-------------------------------------------------------------------- 10 // Preload any models, libraries, etc, here. 11 //-------------------------------------------------------------------- 12 // E.g.: 13 $this->session = \Config\Services::session(); // 加载session 14 $this->db = \Config\Database::connect(); // 加载db连接 15 }
这个BaseController还有一个属性$helpers,是一个数组,可以将想要加载的函数库的名字放在该数组中,在类被实例化后,系统会遍历这个数组,依次加载对应的函数库。
关于自动加载的个人看法:
1. 必须是特别常用的组件才添加到自动加载列表中,不常用的组件用时加载,用完释放,避免资源闲置。
2. 框架虽然会在方法调用结束后释放这些资源,但如果在方法调用中因为某些原因导致不能结束,那么这些资源也会处于占用中,结果可能会导致项目崩溃。
3. 框架只是一个工具,我们要了解他的优点及缺点,才能扬长避短。