前置操作

继承Controller类后可以设置一个$beforeActionList属性来创建前置方法

  1. class Before extends Controller{
  2. protected $beforeActionList= [
  3. 'first',
  4. //one方法执行不调用 second 前置
  5. 'second' =>['except'=>'one'],
  6. //third 前置只能通过调用one 和two方法触发
  7. 'third' =>['pnly'=>'one,two']
  8. ];
  9. protected function first(){
  10. echo 'first<br>';
  11. }
  12. protected function second(){
  13. echo 'second<br>';
  14. }
  15. protected function third(){
  16. echo 'third<br>';
  17. }
  18. public function index(){
  19. return 'index';
  20. }
  21. public function one(){
  22. return 'one';
  23. }
  24. public function two(){
  25. return 'two';
  26. }
  27. }

跳转和重定向

  1. Controller类提供了两个跳转的方法,success(msg,url)和 error(msg);

    1. public function index(){
    2. if($this->flag){
    3. //如果不指定url,则返回$_SERVER['HTTP_REFERER']
    4. $this->success('注册成功','../');
    5. }else{
    6. //自动返回前一页
    7. $this->error('失败!');
    8. }
    9. }
  2. 成功或错误有一个固定的页面模版:’thinkphp/tpl/dispatch_jump.tpl’;

  3. 在app.php配置文件中,我们可以更改自己个性化的跳转页面;

    1. // 默认跳转页面对应的模板文件
    2. 'dispatch_success_tmpl' => Env::get('think_path') . 'tpl/dispatch_jump.tpl',
    3. 'dispatch_error_tmpl' => Env::get('think_path') . 'tpl/dispatch_jump.tpl',
  4. 如果需要自定义跳转页面,可以使用如下的模版变量

image.png

空方法和空控制器

  1. 当访问了一个不存在的方法时,系统会报错,我们可以使用_empty()来拦截;

    1. public function _empty($name){
    2. return '不存在当前方法'.$name;
    3. }
  2. 当访问了一个不存在的控制器时,系统也会报错,我们可以使用Error类来拦截;

    1. class Error{
    2. public function index(Request $request){
    3. return '当前控制器不存在'.$request->controller();
    4. }
    5. }
  3. 系统默认为Error类,如果需要自定义,则在app.php配置文件中修改;

    1. // 默认的空控制器名
    2. 'empty_controller' => 'Error',