Reputation: 4646
I'm aware that methods can be resolved automatically by Laravel within the controller:
//A
class ScriptsController extends Controller {
public function __construct(Script $scripts){ // Script automatically injected
$this->scripts = $scripts;
}
public function store(Request $request, $id){ // Request automatically injected
// do something
}
}
I simply want to do the same thing with any class or method.
// B1
class MyClass extends Controller {
public function __construct(Bar $bar){ // Bar to be automatically injected
$this->bar = $bar;
}
public function doSomething(Foo $foo, $id){ // Foo to be automatically injected
$foo->do();
}
}
Then somewhere else
// B2
$class = new MyClass(); // without an error
$class2 = new MyClass();
$class2->doSomething(); // ditto
There are tutorials about this but rather than answering this directly they tend to have long explanations about how the service provider works etc.
Is there a simple way to add a line somewhere ( Bind
perhaps ?) to have the container resolve the dependencies so that B2
above works?
Upvotes: 0
Views: 2829
Reputation: 2025
I don't think you'd be able to do that with that particular syntax. You can have Laravel automatically inject dependencies for your class, but you'd need to resolve it out of the container in any case.
Please see the documentation here for binding: https://laravel.com/docs/5.3/container#binding and further down, resolving classes from the container.
Upvotes: 1