Laravel 5 IoC container cannot allow context bindings when using injection method

In my Laravel 5 application, I registered a context binding for an interface in a service provider, for example:

$this->app->when('App\Http\Controllers\MyController')
    ->needs('App\Contracts\MyRepositoryInterface')
    ->give('App\Repositories\MyRepostory');

Inside the controller MyController, I have a method index()in which I am trying to enter MyRepositoryInterfaceas follows:

public function index(App\Contracts\MyRepositoryInterface $repo)
{
    // Stuff
}

The problem is that the above does not work and gives this error:

BindingResolutionException in line Container.php 754:

Target [App \ Contracts \ MyRepositoryInterface] does not work.

However, if I change the context binding to a regular binding , as shown below, it works:

$this->app->bind(
    'App\Contracts\MyRepositoryInterface',
    'App\Repositories\MyRepository'
);

, , , :

public function __constructor(App\Contracts\MyRepositoryInterface $repo)
{
    // Stuff
}

: ( )? , Laravel 5?

- ?

, !

+4
3

Laravel 5 (/ 5.0), № 6177.

0

Laravel 5 does not support this because it is not intended to work with methods. A workaround is to extend the ValidatesWhenResolved interface with your own, for example:

namespace Authentication\Requests\Contracts;
use Illuminate\Contracts\Validation\ValidatesWhenResolved;

interface Validatable extends ValidatesWhenResolved {}

And how can you bind to this interface:

$this->app->bind('Authentication\Requests\Contracts\Validatable',
'Authentication\Requests\Login');

This is not DRY.

0
source

All Articles