Laravel: Dependency Injection on methods and closures

Hey, you can type-hint your dependencies on everything!

public function post(Request $request)
{
$request->validate([
// ...
]);
// .. do something}

Call this method with magic

Using a simple string

$result = app()->call('App\MyClass@myMethod');
class MyClass
{
protected $foo;
public function __construct(Foo $foo)
{
$this->foo = $foo;
}
public function myMethod(Bar $bar)
{
return $foo->doSomethingWith($bar);
}
}
public function register()
{
// When someone calls for this class, anywhere, ensure
// the instance is saved inside the container so we
// can use it in other parts of the application.
$this->app->singleton(\App\MyClass::class);
}

Using an instance

$instance = new MyClass($foo);$result = app()->call([$instance, 'myMethod']);$instance->doSomethingMore();

Adding parameters

$result = app()->call('App\MyClass@myMethod', [
'red',
'cool',
]);
$result = app()->call('App\MyClass@myMethod', [
'status' => 'good',
'cool' => true,
'service' => SuperService::class,
]);
app()->call('App\MyClass@myMethod', [
'service' => null,
]);

Default method

$result = app()->call('App\MyClass', [
// ... may be some arguments
], 'defaultMethod');

Calling closure, callbacks and others callables

Methods and Closures

$closure = function (Foo $foo) {
return $foo->doSomething();
};
$result = app()->call($closure);
$closure = function (Foo $foo, string $bar) {
return $foo->doSomethingWith($bar);
};
$result = app()->call($closure, [
'bar' => 'rofl',
]);

Invokables

ReflectionException : Function MyInvokableClass() does not exist
<?phpnamespace App;use \Illuminate\Contracts\Config\Repository as Config;class MyInvokableClass
{
public function __invoke(Config $config)
{
return $config->get('app.env');
}
}
app()->call(new MyInvokableClass);

Graphic Designer graduate. Full Stack Web Developer. Retired Tech & Gaming Editor.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store