Home > Article > Backend Development > In laravel, I inject an object into the parent class, and then I want to inject different implementations of this object according to different subclasses. Is there any way?
I inject an object into the parent class, and then I want to inject different implementations of this object based on different subclasses.
Because the parent class uses this object, I can’t inject it in the subclass, but I need a different implementation.
I control the injected code:
Writing like this won’t work, because the object is injected in the parent class. The place where it is injected in the parent class:
I inject an object into the parent class, and then I want to inject different implementations of this object based on different subclasses.
Because the parent class uses this object, I can’t inject it in the subclass, but I need a different implementation.
I control the injected code:
Writing like this won’t work, because the object is injected in the parent class. The place where it is injected in the parent class:
Method 1: Do not directly inject instances into the action method of the parent class. The parent class obtains related instances from other methods, and the subclass overrides this method and returns the instance injected by itself. For example:
Parent class:
<code class="php">public function update() { $this->validate($this->getRequest(), ...); } protected function getRequest() { return app(Request::class); }</code>
Subcategories:
<code class="php">protected function getRequest() { return app(RoleRequest::class); }</code>
Method 2: Use traits.
Method 3: Inject in __construct. Similar to method 1, the __construct of the parent class does not depend on any parameters, and the __construct of the subclass depends on it at will.
Why is it designed like this?