Friday, March 31, 2017

How to Auto Inject Dependency with Laravel

I'm trying to build a structure that uses dependency injection on lumen.

I Have a Service Layer and repository layer.

I want to inject the repository layer to service layer. Let me try to show you the code

    interface IUserRepostitory {
        public function getByID($id);
    }

    class UserRepository extends BaseRepository implements IRepository{
        public function getByID($id) {
            //Please don't think how this function works, my question about dependency injection
            return $this->findOrFail($id);
        }

    }


   interface IService {
       public function getByID($id);
   }

   class UserService implements IService{

       private $Repository;
       public __construct(IUserRepositor $UserRepository) {
            $this->Repository = $UserRepository
       }

       public function getByID($id) {
             return $this->Repository->getByID($id);
       }
   }

Here I'm registering the dependency resolver.

//Dependency resolver for Repository Layer
class RepositoryServiceProvider extends ServiceProvider {

    public function register()
    {
        $this->app->singleton(IUserRepository::class, function () {
            return new UserRepository();
        });
    }

}

Here I'm registering Service Layer

class ServiceServiceProvider extends ServiceProvider {

    public function register()
    {
        $this->app->singleton(IUserService::class, function () {
            //Here is what I don't like
            //It would be great a solution that automaticly resolve UserRepository.
            return new UserService(new UserRepository());
        });
    }
}

As you see, I want to auto resolve the dependency into UserService. But singleton method need to create the returning object.

Is there a better way for this?

*** note : please don't pay attention on syntax, I'm writing it on lumen but the same problem on laravel.



via fobus

Advertisement