TP5.1 前置操作+空操作+空控制器

1.前置操作  app\index\controller\Demo4

<?php
#前置操作,设置 beforeActionList属性可以指定某个方法为其他方法的前置操作
namespace app\index\controller;
use think\Controller;
class Demo4 extends Controller
{
    protected $beforeActionList = [
        'first',  //first是所有方法(不包含前置操作)的前置操作
        'second' =>  ['except'=>'hello'],  //second是除了hello()以外所有方法的前置操作
        'three'  =>  ['only'=>'hello,data'],//three是只有hello()和data()的前置操作
    ];
    /**
     * [1]数组键名为需要调用的前置方法名
     * [2]数组的值来确定前置方法使用的约束,
        * 2.1 值为空就是指当前方法是所有方法的前置操作
        * 2.2 except属性指定的方法不能使用当前方法为前置操作
        * 2.2 only 只有指定的方法使用当前前置操作
     */
    
    protected function first()
    {
        echo 'first<br/>';
    }
    
    protected function second()
    {
        echo 'second<br/>';
    }
    
    protected function three()
    {
        echo 'three<br/>';
    }

    public function hello()
    {
        return 'hello';
    }
    /**http://localhost:8090/tpjiuzhu30/public/index.php/index/demo4/hello
         * first
         * three
         * hello
         */
    
    public function data()
    {
        return 'data';
    }
    /**
     * http://localhost:8090/tpjiuzhu30/public/index.php/index/demo4/data
         * first
         * second
         * three
         * data
         */
}

2.空操作 app\index\controller\City

<?php
namespace app\index\controller;

/**
 * 空操作是指系统在找不到指定的操作方法的时候,会定位到空操作(_empty)方法来执行,利用这个机制,我们可以实现错误页面和一些URL的优化。
 */
class City
{
    public function _empty($name)
    {
        //把所有城市的操作解析到city方法
        return $this->showCity($name);
    }

    //注意 showCity方法 本身是 protected 方法
    protected function showCity($name)
    {
        //和$name这个城市相关的处理
        return '当前城市' . $name;
    }
}

/**
 * 接下来,我们就可以在浏览器里面输入
 * http://serverName/index/city/beijing/
 * http://serverName/index/city/shanghai/
 * http://serverName/index/city/shenzhen/
 * 由于City并没有定义beijing、shanghai或者shenzhen操作方法,因此系统会定位到空操作方法_empty中去解析
 * ,_empty方法的参数就是当前URL里面的操作名,因此会看到依次输出的结果是:
 * 当前城市:beijing
 * 当前城市:shanghai
 * 当前城市:shenzhen
 */

3.空控制器 app\index\controller\Error

<?php
namespace app\index\controller;
use think\Request;
/**
 * 空控制器的概念是指当系统找不到指定的控制器名称的时候,系统会尝试定位空控制器(Error),
 * 利用这个机制我们可以用来定制错误页面和进行URL的优化。
 */
class Error{
    public function index(Request $request)
    {
        //根据当前控制器名来判断要执行那个城市的操作
        $cityName = $request->controller();
        return $this->city($cityName);
    }
    
    //注意 city方法 本身是 protected 方法
    protected function city($name)
    {
        //和$name这个城市相关的处理
         return '当前城市' . $name;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值