Vincent Decaux
Vincent Decaux

Reputation: 10714

Laravel extends class with constructor using DI

I have created a small CRUD controller, I need to inject FormBuilder in the __construct() of this CRUD controller

class CrudController extends Controller
{
    private $formBuilder;

    /**
     * CrudController constructor.
     * @param FormBuilder $formBuilder
     */
    public function __construct(FormBuilder $formBuilder)
    {
        $this->middleware('auth');
        $this->formBuilder = $formBuilder;
        // .... 

My question is : can I extends this class without injecting FormBuilder to each child ? For now I have :

class LevelsCrudController extends CrudController
{
    public function __construct(FormBuilder $formBuilder)
    {
        parent::__construct($formBuilder);
        // .....

Which is really redondant, any workaround ?

Upvotes: 1

Views: 269

Answers (1)

Chin Leung
Chin Leung

Reputation: 14941

If you do not want to have a FormBuilder $formBuilder in your child controller's construct, you could pass it as a param only when you call the parent's construct like this:

parent::__construct(resolve(FormBuilder::class));

Otherwise, you could remove it completely from the parent's constructor and resolve it inside the parent constructor like this:

class CrudController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        $this->formBuilder = resolve(FormBuilder::class);

        // ...
    }
}

And then in your child, you can simple call:

public function __construct()
{
    parent::__construct();

    // ...
}

Upvotes: 1

Related Questions