dongshang4984 2015-03-30 09:54
浏览 363
已采纳

各种Laravel控制器方法之间的通用逻辑

Let's say I have an URL like this:

/city/nyc   (display info about new york city)

and another like this:

/city/nyc/streets   (display a list of Street of nyc)

I can bind them to a method like this:

Route::get('city/{city}', 'CityController@showCity');
Route::get('city/{city}/streets', 'CityController@showCityStreet');

The problem is that I need to execute some checks on the city (for example if {city} is present in the database) on both methods. I could create a method and call them in both like this:

class CityController {

    private function cityCommonCheck($city) {
       // check
    }

    public function showCity($city) {
      $this->cityCommonCheck($city);

      // other logic
    }

    public function showCityStreet($city) {
      $this->cityCommonCheck($city);

      // other logic
    }
}

Is there any better way?

  • 写回答

2条回答 默认 最新

  • doulu7921 2015-03-30 11:12
    关注

    I think best way to do this, you can move common logic into a Model.So your code would like below.

    class CityController {
    
      public function showCity($city) {
          City::cityCommonCheck($city);  
      }
    
      public function showCityStreet($city) {
        City::cityCommonCheck($city);
      }
    }
    

    model class

    class City{
        public static function cityCommonCheck($city) {
          //put here your logic
        }
    }
    

    In this way you could invoke cityCommonCheck function from any controller.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题