1

Question: How can I inject a disk in my code (constructors or controller methods)?

Related to: https://laravel.com/docs/5.4/filesystem#obtaining-disk-instances

What I want is to do something like

function __construct(Disk $disk)
{

}

instead of this

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

later edit 1:

Using all the time $disk = Storage::disk('files'); in my service classes or controllers looks to me a litle bit "hardcoded". I might have differente service classes like, SendImageOnEmail, OptimizeImage and the disk instance its an infrastructure dependency. To me it seems that is should be injected trough constructor.

user237329
  • 809
  • 1
  • 10
  • 27
  • 1
    Why do you want to use the first option rather than second? and you don't need to pass `Disk` in the constructor as i cannot see any benefits of injecting the `Disk` into the constructor. Could you elaborate more? – PaladiN May 04 '17 at 11:06
  • Added a later edit on the original comment – user237329 May 04 '17 at 11:10

1 Answers1

2

You could create a class that returns your Storage method and inject it into the constructor of the class you want to use the method.

I am providing only the dummy model for your question. You could do something like this:

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

On your controller which uses the disk method:

public $storage;

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

Now you could dynamically get the storage from the StorageType class and use it anwhere in that class using:

$this->storage->getStorage();
PaladiN
  • 4,625
  • 8
  • 41
  • 66