mardi 27 octobre 2015

Dependecy Injection Hell. How should you use depency injection

I been using Laravel framework, and learned some patterns like Repository and also stumbled on Dependency Injection.

I am still lost in the wild and stumble in this very special code, which uses binding interfaces to a class and dependency Injection which made me question how does it handle this kind of code.

consider this following code are working (which are really working)

this class DataRepository was injected to UserRepository. (I don't know how laravel do its DI)

class UserRepository implements UserRepositoryInterface{

    public function __construct(DataRepository dataRepository){

    }
}

now, on this class DataRepository, UserRepository class was injected. (What?) Which it actually works.

class DataRepository implements DataRepositoryInterface{

    public function __construct(UserRepository userRepository){

    }
}

and this is the only thing you do, so you can use it on your controller

 $this->app->bind('App\Blits\Contracts\UserRepositoryInterface', 'App\Blits\Repository\UserRepository');
 $this->app->bind('App\Blits\Contracts\DataRepositoryInterface', 'App\Blits\Repository\DataRepository');

sample controller that works! (Wow! Now I am lost)

class MyAwesomeController extends Controller{

     public function __construct(UserRepository userRepository, DataRepository dataRepository){

    }
}

Now, my problem is How do you instantiate UserRepository class

the problem :

new UserRepository( new DataRepository ( new UserRepository( new DataRepository ( ... now what?) )) );

Did I understand DI right?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire