Laravel 4 - Child constructor call parent constructor with dependency injection

后端 未结 6 1844
死守一世寂寞
死守一世寂寞 2021-02-05 02:53

I\'m building a CMS using Laravel 4 and I have a base admin controller for the admin pages that looks something like this:

class AdminController extends BaseCont         


        
6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-05 03:21

    I know this is a super old question, but I just finished grinding on a similar question on my current project and came to an understanding with the issue at hand.

    The basic underlying question here is:

    If I'm extending a parent class that has a constructor. That constructor has injected dependancies and all of it's dependencies are already documented in the parent itself. Why do I have to include the parent's dependencies again in my child class?

    I ran into this same issue.

    My parent class requires 3 different dependencies. They're injected via the constructor:

    node           = $node;
            $this->template       = $template;
            $this->placeholder    = $placeholder;
        }
    

    The class is an abstract class so I can never instantiate it on it's own. When I extend the class, I still need to include all of those dependencies and their use references in the child's constructor:

    extractor      = $extractor;
            $this->templateFiller = $templateFiller;
            parent::__construct($node, $template, $placeholder);
        }
    

    Including the use statements for the 3 parent dependencies in each class seemed like duplicate code since they're already defined in the parent constructor. My thought was to remove the parent use statements as they'll always need to be defined in the child class that extends the parent.

    What I realized is that including the use for the dependencies in the parent class and including the class names in the parent's constructor are ONLY needed for type hinting in the parent.

    If you remove the use statements from the parent and the type hinted class name from the parents constructor, you get:

    node           = $node;
            $this->template       = $template;
            $this->placeholder    = $placeholder;
        }
    

    Without the use statements and type hinting from the parent, it can no longer guarantee the type of class being passed to it's constructor because it has no way of knowing. You could construct from your child class with anything and the parent would accept it.

    It does seem like double entry of code, but really in your paren't you're not constructing with the dependencies laid out in the parent, you're verifying that the child is sending in the correct types.

提交回复
热议问题