ackerchez
ackerchez

Reputation: 1744

Laravel Common Services Through Inheritance

Question.

I have a bunch of controllers that are using a certain set of services. I was wondering if it is possible / right to utilize inheritance to save me from having to inject them into controllers all the time. This is what I was planning on doing.

class MasterController extends controller{
    public function _construct(){
            $this->userData = App::make(UserService::class)
            $this->fooData = App::make(FooService::class)
    }
}

class UserController extends MasterController {
    public function __construct(BashService $bashService){
        parent::__construct();
        $this->bashData = $bashService;
    }

    public function someFunction(){
        $something = $this->userData->doUserSomething();
    }
}

Is this a good idea to do? A really bad idea to do? Why or why not? I thought this might save me from having to inject common services again and again into controllers.

Thanks!

Upvotes: 5

Views: 470

Answers (1)

Sagar Ahuja
Sagar Ahuja

Reputation: 724

Question:

I was wondering if it is possible/right to utilize inheritance to save me from having to inject them into controllers all the time.

Answer:

  1. Yes it is possible and it is right to utilize inheritance as by following this, you will keep your controller clean which means you can have functions in your controller but the function will lead to a different function implemented or inherited from a different class.

Question:

Is this a good idea to do?

Answer:

  1. Obviously, A big YES it is a good idea as I have mentioned above keeping your controller clean is the best practice one can follow since your methods will be separated from the business logic where you implement all the fetching and posting and calculation and what not since your controller is clean and all the methods actions return from a different class with accurate response eg(true or false).

Question:

Why or why not?

Answer:

  1. Since I have explained most of the part, I would further like to go with to suggest you the repository pattern so basically by the word repository I mean this :

    • A source code repository is a file archive and web hosting facility where a large amount of source code, for software or for web pages, is kept, either publicly or privately. They are often used by open-source software projects and other multi-developer projects to handle various versions.

    In laravel you can follow repository pattern to code your project which is currently found the best practice.

    You can do a google search too on laravel repository pattern.

    I have an example which will make you understand this.

Upvotes: 2

Related Questions