2015-02-05 61 views
1

我一直在關注裝飾存儲庫的真正有用的Laracast,以便提供從模型中獲取數據的不同層。Laravel接口注入裝飾存儲庫

在實施它時,我爲我的Client模型製作了兩個存儲庫,它們都實現了ClientRepository接口(緩存回購和db回購)。

然後,我做了一個服務提供商,並相應地註冊了他們。

以同樣的方式,我做了同樣的FxRateRepository。下面是不註冊的服務提供商:

// Providers/DatabaseServiceProvider 

public function register() 
{ 
    // Register the fx repositories 
    $this->app->singleton('\repositories\FxRateRepository', function() 
    { 
     return new CacheFxRateRepository(new DbFxRateRepository); 
    }); 

    // Register the client repositories 
    $this->app->singleton('\repositories\ClientRepository', function() 
    { 
     return new CacheClientRepository(new DbClientRepository); 
    }); 
} 

現在,這一切都很好,並且效果很好...直到我意識到我需要DbClientRepositoryFxRateRepository一個實例。在我的服務提供商中,我「新建」了每個回購的實例,並將它們作爲依賴關係傳遞給父回購。

顯然我無法將接口傳遞到DbClientRepository那麼我該如何告訴Laravel將FxRateRepository的實現注入我的DbClientRepository

我嘗試了TYPE-暗示在DbClientRepository的構造函數,但我得到一個異常:傳遞給倉庫

class DbClientRepository implements ClientRepository { 
    private $fxRepo; 
    public function __construct(FxRateRepository $fxRepo) 
    { 
     $this->fxRepo = $fxRepo; 
    } 
} 

參數1 \ DbClientRepository :: __結構() 必須是倉庫的實例\ FxRateRepository,沒有給出

我可能錯過了IoC容器的一些方便的功能,但將不勝感激關於如何實現這一目標的任何建議?

回答

1

型暗示在DbClientRepository構造函數的依賴關係是正確的,但是你再不能只是實例化它由new DbClientRepository但不得不從App::make() IoC容器解決它,以便Laravel可以採取DI的護理:

$this->app->singleton('\repositories\ClientRepository', function() 
{ 
    return new CacheClientRepository(App::make('repositories\DbClientRepository'); 
}); 

取而代之的是門面,你也可以只使用$app對象:

$this->app->singleton('\repositories\ClientRepository', function($app) 
{ 
    return new CacheClientRepository($app->make('repositories\DbClientRepository'); 
}); 
+0

完美,一個可行的治療。 – harryg 2015-02-05 15:12:55