🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
#### 控制器初始化 如果控制器下面的每个操作都需要执行一些公共的操作(例如权限和登录检查),有两种方法,如果你没有继承系统的控制器基类,可以使用架构方法来进行初始化,例如: ~~~ <?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 如果应用的所有控制器都需要执行一些公共操作,则只需要让应用控制器都统一继承一个公共的控制器类,然后在该公共控制器类里面定义初始化方法即可。 例如在公共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()`方法,参考后面的跳转和重定向内容。不过,初始化方法中仍然支持抛出异常。