CI4框架应用六 - 控制器应用
2024-10-09 08:50:26
这节我们来分析一下控制器的应用,我们看到系统提供的控制器都是继承自一个BaseController,我们来分析一下这个BaseController的作用
use CodeIgniter\Controller; class BaseController extends Controller
{ /**
* An array of helpers to be loaded automatically upon
* class instantiation. These helpers will be available
* to all other controllers that extend BaseController.
*
* @var array
*/
protected $helpers = []; /**
* Constructor.
*/
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger); //--------------------------------------------------------------------
// Preload any models, libraries, etc, here.
//--------------------------------------------------------------------
// E.g.:
// $this->session = \Config\Services::session();
}
}
这个控制器的意义就是一个加载组件的场所,把一些常用的组件转成该类的属性,那么其它的控制器继承了这个类也就获得了这些属性,可以在开发中直接使用了,或是预加载一些函数库,在开发中可以直接使用这些函数库里的函数。
我们先来看一下initController这个方法,这个方法的说明是构造器,功能类似于构造方法,但这个只是一个普通的方法,是在类被实例化后手动调用的,这个方法接受三个参数,分别是:
1. $request 请求对象
2. $response 响应对象
3. $logger 日志对象
在构造器方法执行后会转成自身的属性:
1. $this->request
2. $this->response
3. $this->logger
其中 $this->request 特别重要,和用户请求相关的所有信息都可以从这个对象获得
我们看到这个构造器方法还可以加载任何模型,库等等, 例如:
/**
* Constructor.
*/
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger); //--------------------------------------------------------------------
// Preload any models, libraries, etc, here.
//--------------------------------------------------------------------
// E.g.:
$this->session = \Config\Services::session(); // 加载session
$this->db = \Config\Database::connect(); // 加载db连接
}
这个BaseController还有一个属性$helpers,是一个数组,可以将想要加载的函数库的名字放在该数组中,在类被实例化后,系统会遍历这个数组,依次加载对应的函数库。
最新文章
- opengl 读取3ds(stl)文件
- HT for Web基础动画介绍
- 如何解决adb devices 端口被占用的问题zz
- 【HDOJ】【4405】Aeroplane chess飞行棋
- vmware克隆centos6.5 导致 system eth0 不可用解决办法
- C语言解析日志,存储数据到伯克利DB
- symfony的安装
- Webx MVC分析(转)
- Linux/Windows 文件交互读取转义字符变换
- Powershell-创建Module
- H5本地存储sessionStorage和localStorage的区别
- Mysql时间差计算
- Javascript 中调参数的脚本onclick=";select(this)"; this 怎么解释
- 给予Java初学者的学习路线建议
- The last access date is not changed even after reading the file on Windows 7
- 排名前16的Java工具类
- docker 存储驱动之 overlay2
- Jquery Easy UI初步学习(一)
- Python接口测试实战5(上) - Git及Jenkins持续集成
- 02、Universal app 中按钮图标使用