Created
September 25, 2014 01:01
-
-
Save bkuhl/f44d05680d36b8f11910 to your computer and use it in GitHub Desktop.
Laravel 5.0 Feature Request: Advanced Dependency Injection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Sometimes a class needs 1 specific instance of something, but several generic instances and it | |
* becomes a bit of a pain to instantiate. I suggest making this easier... | |
*/ | |
// In Laravel 4.3 we need to do it this way | |
MyClass { | |
public function __construct(ParamOne $paramOne) | |
{ | |
//we need a particular instance of this one that another | |
//class may have modified or built for us in a particular way | |
//Maybe it's a specific instance of a model... | |
$this->paramOne = $paramOne; | |
//we just need any old instance of these, but we use | |
//App::make() because it's cleaner to do it here than | |
//where I'm App::make()ing MyClass | |
$this->depOne = App::make('depOne'); | |
$this->depTwo = App::make('depTwo'); | |
$this->depThree = App::make('depThree'); | |
$this->depFour = App::make('depFour'); | |
} | |
} | |
//But what if in Laravel 5.0 it worked this way... | |
$myClass = App::make('MyClass', [ | |
$paramOne | |
]); | |
MyClass { | |
//Laravel could recognize which dependencies were passed and which weren't and auto inject those that weren't | |
public function __construct(ParamOne $paramOne, DepOne $depOne, DepTwo $depTwo, DepThree $depThree, DepFour $depFour) | |
{ | |
//Laravel knew we were passing this one, so this | |
//is the specific instance we wanted to pass | |
$this->paramOne = $paramOne; | |
//These would be injected | |
$this->depOne = $depOne; | |
$this->depTwo = $depTwo; | |
$this->depThree = $depThree; | |
$this->depFour = $depFour; | |
} | |
} |
I really like the IoC contexts, but I think this could be done without the need for additional code to be written in service providers. Using reflection the IoC container, while resolving dependencies, could recognize that ParamOne
has been passed and use that instead of resolving a new instance. With the ones it doesn't recognize it could resolve.
OK will look into it.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In Laravel 5: