zoukankan      html  css  js  c++  java
  • ThinkPHP

    空操作

    空操作是指系统在找不到指定的操作方法的时候,
    会定位到空操作(_empty)方法来执行,利用这个机制,
    我们可以实现错误页面和一些URL的优化。

    例如,下面我们用空操作功能来实现一个城市切换的功能。
    我们只需要给CityAction类定义一个_empty (空操作)方法:

    <?php
    class CityAction extends Action{
        public function _empty($name){
            //把所有城市的操作解析到city方法
            $this->city($name);
        }
        
        //注意 city方法 本身是 protected 方法
        protected function city($name){
            //和$name这个城市相关的处理
             echo '当前城市' . $name;
        }
    }
    

     
    接下来,我们就可以在浏览器里面输入

    http://serverName/index.php/City/beijing/
    http://serverName/index.php/City/shanghai/
    http://serverName/index.php/City/shenzhen/

    由于CityAction并没有定义beijing、shanghai或者shenzhen操作方法,
    因此系统会定位到空操作方法 _empty中去解析,_empty方法的参数就是当前URL里面的操作名,
    因此会看到依次输出的结果是:

    当前城市:beijing
    当前城市:shanghai
    当前城市:shenzhen






    空模块

    空模块的概念是指当系统找不到指定的模块名称的时候,
    系统会尝试定位空模块(EmptyAction),利用这个机制我们可以用来定制错误页面和进行URL的优化。

    现在我们把前面的需求进一步,把URL由
    原来的 http://serverName/index.php/City/shanghai/
    变成 http://serverName/index.php/shanghai/

    这样更加简单的方式,如果按照传统的模式,我们必须给每个城市定义一个Action类,
    然后在每个Action类的index方法里面进行处理。 可是如果使用空模块功能,这个问题就可以迎刃而解了。
    我们可以给项目定义一个EmptyAction类

    <?php
    class EmptyAction extends Action{
        public function index(){
            //根据当前模块名来判断要执行那个城市的操作
             $cityName = MODULE_NAME;
            $this->city($cityName);
        }
        //注意 city方法 本身是 protected 方法
        protected function city($name){
            //和$name这个城市相关的处理
             echo '当前城市' . $name;
        }
    }
    

       
    接下来,我们就可以在浏览器里面输入
    http://serverName/index.php/beijing/
    http://serverName/index.php/shanghai/
    http://serverName/index.php/shenzhen/

    由于系统并不存在beijing、shanghai或者shenzhen模块,
    因此会定位到空模块(EmptyAction)去执行,会看到依次输出的结果是:
    当前城市:beijing
    当前城市:shanghai
    当前城市:shenzhen


    空模块和空操作还可以同时使用,用以完成更加复杂的操作。

  • 相关阅读:
    [LeetCode] Trips and Users 旅行和用户
    [LeetCode] Rising Temperature 上升温度
    [LeetCode] Delete Duplicate Emails 删除重复邮箱
    [LeetCode] Department Top Three Salaries 系里前三高薪水
    Spring boot Jackson基本演绎法&devtools热部署
    使用spring tool suite(STS)工具创建spring boot项目和出现错误后的处理
    Spring Boot 2.0官方文档之 Actuator
    springboot 使用webflux响应式开发教程(二)
    SpringBoot在自定义类中调用service层等Spring其他层
    springBoot单元测试-模拟MVC测试
  • 原文地址:https://www.cnblogs.com/KTblog/p/5180292.html
Copyright © 2011-2022 走看看