2017-05-04 44 views
-1

問題:如何在我的代碼(構造函數或控制器方法)中注入磁盤?在Laravel中注入磁盤實例

相關:https://laravel.com/docs/5.4/filesystem#obtaining-disk-instances

我想要的是像做

function __construct(Disk $disk) 
{ 

} 

function __construct(Disk $disk) 
{ 
    $disk = Storage::disk('files'); 
} 

後來編輯1代替:

利用所有的時間$disk = Storage::disk('files');在我的服務類或控制器看起來給我一點點「硬編碼」。我可能有不同的服務類,如SendImageOnEmail,OptimizeImage和磁盤實例它的基礎設施依賴。對我來說,似乎應該注入到構造函數中。

+1

爲什麼要使用第一個選項而不是第二個選項?你不需要在構造函數中傳遞'Disk',因爲我看不到在構造函數中注入'Disk'的好處。你能詳細說明嗎? – PaladiN

+0

在原始評論中添加了以後的修改 – user237329

回答

1

您可以創建一個返回Storage method的類,並將其注入要使用該方法的類的構造函數中。

我只爲您的問題提供虛擬模型。你可以做這樣的事情:

Class StorageType 
{ 
    public function getStorage() 
    { 
     //do something that gets the storage type 
     $storage = Storage::disk('files'); // you could manipulate your storage method and return to the class you are using. 
     return $storage; 
    } 
} 

在您的控制器,它使用的磁盤方法:

public $storage; 

function __construct(StorageType $storageType) 
{ 
    $this->storage = $storageType; 
} 

現在你可以動態獲取從StorageType類的存儲和使用該類anwhere使用它:

$this->storage->getStorage();