多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
### 使用控制器基类 系统内置了一个控制器基类`think\Controller`,本讲内容就是来讲解下这个控制器基类的功能和用法。 要使用控制器基类的功能,有两种方式:继承`think\Controller`基类和使用`Trait`引入`traits\controller\Jump`,继承可以使用基类的完整功能,`Trait`引入的话只有部分功能,后面我们会提到。 #### 控制器初始化 如果控制器下面的每个操作都需要执行一些公共的操作(例如,权限和登录检查),有两种方法,如果你没有继承系统的控制器基类,可以使用架构方法来进行初始化,例如: ~~~ <?php namespace app\index\controller; class Index { // 架构方法 public function __construct() { echo 'init<br/>'; } public function hello() { return 'hello,world'; } public function test() { return 'test'; } } ~~~ 如果已经继承了系统控制器基类,那么可以使用控制器初始化方法: ~~~ <?php namespace app\index\controller; use think\Controller; class Index extends Controller { // 初始化 protected function _initialize() { echo 'init<br/>'; } public function hello() { return 'hello,world'; } public function test() { return 'test'; } } ~~~ 无论使用何种方式,当我们访问下面的URL地址:`http://tp5.com/index/index/hello`页面输出结果为: > init > hello,world 而当访问:`http://tp5.com/index/index/test`页面输出结果为: > > init > test 如果应用的所有控制器都需要执行一些公共操作,则只需要让应用控制器都统一继承一个公共的控制器类,然后在该公共控制器类里面定义初始化方法即可。 例如,在公共Base控制器类里面定义初始化方法: ~~~ <?php namespace app\index\controller; use think\Controller; class Base extends Controller { // 初始化 protected function _initialize() { echo 'init<br/>'; } } ~~~ 然后其它控制器都继承Base控制器类: ~~~ <?php namespace app\index\controller; use app\index\controller\Base; class Index extends Base { public function hello() { return 'hello,world'; } public function test() { return 'test'; } } ~~~ > 初始化方法里面的return操作是无效的,也不能使用redirect助手函数进行重定向,如果你是要进行重定向操作(例如权限检查后的跳转)请使用$this->redirect()方法,参考后面的跳转和重定向内容。不过,初始化方法中仍然支持抛出异常。