处理具有类似操作的路线的最佳做法是什么? [关闭]

I'm working on a picture gallery web application. It has many access routes, they all should render a gallery the same way, the only difference is the order of the pictures.

so for example:

mysite.com/favorites -> shows all the pics ordered by number of favorites
mysite.com/views -> shows all the pics ordered by number of views
mysite.com/date -> shows all the pics ordered by date
mysite.com/votes -> shows all the pics ordered by votes

Being all these actions so similar between them, Is it a good practice to define one action per route on the controller and pass the order as parameter? Or this logic should be handled in the model?

If actions are so similar that differ from a parameter, it could make senss to have one action that accept that parameter. That last is not a rule, just a preference.

In your specific case you can handle it as follows by using one route with parameter:

Route::get('{orderBy}', 'GalleryController@showPics')

Then in your controller you will have something as follows:

class GalleryController extends BaseController
{
    public function showPics($orderBy)
    {
        $pics = $this->service->getPics($orderBy);
        return View::make('gallery')->with('pics', $pics);
    }
}

Though it will work fine, there is some points to consider:

  1. It is more semantic to have controller with specialized action i.e.: showFavorites, showMostViewed, showRecents, showMostVoted.
  2. Think about the view. If you plan to deliver different view, different nested child with different data set, it is better to have an action for each case.
  3. Code readability. Imagine the controller with several if statements, several return statements, all wrapped in a big try-catch block that have multiple catch clauses... If you can avoid a brain lapse to the next programmer with a spaghetti code, consider it.