2017-03-31 77 views
1

我試圖構建一個在流明上使用依賴注入的結構。如何使用Laravel自動注入依賴關係

我有一個服務層和存儲庫層。

我想將資源庫層注入服務層。讓我試着向你展示代碼

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); 
     } 
    } 

這裏我註冊了依賴關係解析器。

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

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

} 

在這裏,我註冊服務層

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()); 
     }); 
    } 
} 

正如你看到的,我想自動解決依賴到UserService。但是單例方法需要創建返回對象。

有沒有更好的方法呢?

***注意:請不要關注語法,我在流明上寫它,但laravel上的問題相同。

回答

1

一旦綁定UserRepositoryIUserRepository,你然後可以通過與make功能解決實例化IUserServiceIUserRepository

修改您的ServiceServiceProvider這樣:

class ServiceServiceProvider extends ServiceProvider 
{ 
    public function register() 
    { 
     $this->app->singleton(IUserService::class, function ($app) { 
      return new UserService($app->make(IUserRepository::class)); 
     }); 
    } 
} 
+0

偉大的作品,謝謝! – fobus

相關問題