如何在Laravel中执行一个路由上的两个函数?
如何在Laravel中执行一个路由上的两个函数?
我有一个问题,我希望我的路由/browse既能显示一些元素,又能通过一个编写的函数来检查一个条件,这是两个不同的函数,但我希望它们在一个路由上运行,这样可能吗?\nweb.php\n
Route::get('/browse',[PlantsController::class, 'browse'])->name('browse'); Route::get('check',[PlantsController::class, 'checkForWatering'])->name('check');
\n我尝试过像这样做:\n
public function browse() { $this->checkForWatering(); $this->displayPlants(); }
\n但结果是一个空白页面。\n以下是我的函数:\n
public function checkForWatering() { $all = DB::table('plants') ->select('*') ->get(); foreach ($all as $result) { $now = Carbon::now(); $nextWatering = (new Carbon ($result->watered_at)) ->addDays($result->watering_frequency); $daysPast = $nextWatering->diffInDays($now); $query = DB::table('plants') ->where('watering_frequency', '>=', $daysPast) ->get(); $query->isEmpty() ? $result = true : $result = false; return redirect()->route('browse')->with('result',$result); } } public function displayPlants(){ $now = new Carbon(); $plants = DB::table('plants') ->where('user_id', '=', auth()->id()) ->orderBy('watered_at', 'desc') ->get(); foreach ($plants as $plant) { $plant->watered_at = Carbon::parse($plant->watered_at) ->diffForHumans(); $plant->fertilized_at = Carbon::parse($plant->fertilized_at) ->diffForHumans(); } return view('browse')->with('plants',$plants); }
问题出现的原因是在Laravel中执行一个路由时,只能执行一个函数,但是需要同时执行两个函数。
解决方法是在路由中定义一个函数,然后在该函数中调用需要执行的两个函数。具体操作如下:
public function browse() { $response = $this->checkForWatering(); if (!empty($response)) { // 如果checkForWatering函数返回了一个响应对象,则直接返回该对象 return $response; } return $this->displayPlants(); }
通过以上代码,我们可以在同一个路由中同时执行checkForWatering和displayPlants这两个函数。
问题出现的原因是在Laravel中如何在一个路由上执行两个函数。解决方法是在返回之前调用另一个控制器方法并将响应赋值给一个变量。
public function browse() { $response = $this->checkForWatering(); // Checks if the Response of checkForWatering exists return !empty($response) ? $response : $this->displayPlants(); }
虽然可以在一个控制器方法中调用两个控制器方法,但最好将这些逻辑从控制器中分离出来,放到它们自己的类中。
软件架构是非常主观的,但我建议查阅一些关于控制器的资源,了解一些人们在应用程序中如何布局控制器的建议,相信这将帮助你解决类似的问题,比如想要在两个控制器中调用相同的代码。
以下是一些相关资源:
- [How much business logic should be allowed to exist in the controller](https://softwareengineering.stackexchange.com/questions/26438/how-much-business-logic-should-be-allowed-to-exist-in-the-controller-layer)
- [MVC (Laravel) where to add logic](https://stackoverflow.com/questions/23595036)
- [Keeping your Laravel applications DRY with single action classes](https://medium.com/_collin/keeping-your-laravel-applications-dry-with-single-action-classes-6a950ec54d1d)
- [Put Your Laravel Controllers on a Diet](https://matthewdaly.co.uk/blog/2018/02/18/put-your-laravel-controllers-on-a-diet)