Ivan_Iliev's avatar

Need help to understand which way is better to structure a few controllers in my project

Hello guys, I am bulding a website using laravel, which is going to have a blog, videos and food recipes sections. So i want to have categories /taxonomies/ for each of those post types. So i have separate models and tables for each one of them.

class PostCategory extends Model / Videos / Recipes
{
    // has many posts/videos/recipes
}


and also separate resource controller for each one of them like:

class PostCategoriesController / Videos / Recipes
{
    //
}

I also want different routes for each one of them like:

/categories/posts /categories/videos /categories recipes

So i define my routes like this:

Route::resource('categories/posts','PostCategoriesController',['as' => 'categories'])->
                parameters(['posts' => 'category']); // The sam efor videos, recipes

But then the logic in those controllers is pretty much the same and the views are pretty much the same. How could i make this simpler ? Does it make sense to create a CategoriesController class and consolidate the views into one and do it like this:

abstract class CategoriesController extends Controller
{
    protected $post_type;
    protected $post_type_model;

    public function __construct() {
        if ( !$this->post_type) {
            // throw exception
        }

        switch ( $this->post_type ) {
            case 'post': $this->post_type_model= new PostCategory;
            case 'video': $this->post_type_model= new VideoCategory;
            case 'recipe': $this->post_type_model= new RecipeCategory;
            default: 
            // Throw exception if there is no model assigned
            break;
        }
    }

    public function edit($id)
    {
        $category = $this->post_type_model->find($id);

        $data = [
            'category' => $category
        ];

        return view('admin.categories.edit')->with($data);
    }

    // rest of the logic here for index,delete,update etc..
}

and then

class VideoCategoriesController extends CategoriesController
{
    protected $post_type = 'video';
}

Any toughts?

0 likes
2 replies
Ivan_Iliev's avatar

@martinbean Not true. I dont want to share categories between them and i want a single post to have a only 1 category. I would have used that if that was the case but its not. Thanks anyway :)

Please or to participate in this conversation.