jeudi 28 janvier 2016

Avoiding duplicate code in two controllers in Laravel 5.1

I have a route in Laravel 5.1 that will accept a generic permalink and will need to determine what object it belongs to (for example is it a permalink for a "Blog" or a "Story"?).

The route looks like this:

// .... Every other route in the routes.php file //
Route::get('{generic_url}', 'CMSController@generic');

Then the code in the my controller looks like this:

public function generic($generic_url) {
    $blog = Blog::where('permalink', $generic_url)->first();
    if(!is_null($blog)) {
        // Load a blog entry page
    }

    // Something basically the same as above but for Story
}

I also have this route in my routes.php file to view a blog post:

Route::get('/blog/{blog_id}', 'BlogController@view');

The purpose of that second route was for me rough in the view a blog post page as well as a quick way for me to debug a particular post.

I am hoping to avoid having to put view code in two separate controllers. My first thought was to try and find a way to have CMSController call the view action in the BlogController. It sounds like a terrible idea to me and some searching around confirms that it is a terrible idea.

My question is, what is the best way to handle this situation?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire