前置操作
继承Controller类后可以设置一个$beforeActionList属性来创建前置方法
class Before extends Controller{
protected $beforeActionList= [
'first',
//one方法执行不调用 second 前置
'second' =>['except'=>'one'],
//third 前置只能通过调用one 和two方法触发
'third' =>['pnly'=>'one,two']
];
protected function first(){
echo 'first<br>';
}
protected function second(){
echo 'second<br>';
}
protected function third(){
echo 'third<br>';
}
public function index(){
return 'index';
}
public function one(){
return 'one';
}
public function two(){
return 'two';
}
}
跳转和重定向
Controller类提供了两个跳转的方法,success(msg,url)和 error(msg);
public function index(){
if($this->flag){
//如果不指定url,则返回$_SERVER['HTTP_REFERER']
$this->success('注册成功','../');
}else{
//自动返回前一页
$this->error('失败!');
}
}
成功或错误有一个固定的页面模版:’thinkphp/tpl/dispatch_jump.tpl’;
在app.php配置文件中,我们可以更改自己个性化的跳转页面;
// 默认跳转页面对应的模板文件
'dispatch_success_tmpl' => Env::get('think_path') . 'tpl/dispatch_jump.tpl',
'dispatch_error_tmpl' => Env::get('think_path') . 'tpl/dispatch_jump.tpl',
如果需要自定义跳转页面,可以使用如下的模版变量
空方法和空控制器
当访问了一个不存在的方法时,系统会报错,我们可以使用_empty()来拦截;
public function _empty($name){
return '不存在当前方法'.$name;
}
当访问了一个不存在的控制器时,系统也会报错,我们可以使用Error类来拦截;
class Error{
public function index(Request $request){
return '当前控制器不存在'.$request->controller();
}
}
系统默认为Error类,如果需要自定义,则在app.php配置文件中修改;
// 默认的空控制器名
'empty_controller' => 'Error',