code review

Posted 1 month ago by michaelnguyen547

I have several models that upload to S3 , in all of them, I have 3 main functions

    public function retrieveFileUrl()
    {
        return ($this->file) ? Storage::disk('s3')->temporaryUrl($this->file, now()->addMinutes(5)) : '';
    }


    public function uploadToS3($newFile, $path)
    {
        $this->deleteFromS3();

        $this->file = Storage::disk('s3')->putFile($path, $newFile);

        $this->save();
    }

    private function deleteFromS3()
    {
        if ($this->file) {
            Storage::disk('s3')->delete($this->file);
        }
    }

I figure that I can create a class S3Uploader to handler all uploading to S3. I need

  • $model // to tell which table I am working on, can be user, document
  • $attribute // which column I am working on, $user->photo, $document->file
class S3Uploader
{
    public static function upload($model, $attribute, $request, $path)
    {
        rnew self($model, $attribute, $request, $path)->uploadToS3();
    }

    public function __construct(Model $model, $attribute, $request, $path)
    {
        $this->model = $model;
        $this->attribute = $attribute;
        $this->path = $path;
        $this->request = $request;
    }

    public uploadToS3() {

        if ($this->request->hasFile($this->attribute)) {
            $this->deleteFromS3();
            $this->model->{$this->attribute} = Storage::disk('s3')->putFile($this->path, $this->request->file($this->attribute));
            $this->model->save();
        }
    }

    public retrieveFromS3() {
        return ($this->model->{$this->attribute}) ? Storage::disk('s3')->temporaryUrl($this->model->$attribute, now()->addMinutes(5)) : asset('placeholder.jpg');
    }

    private deleteFromS3($attribute) {
        if ($this->model->{$this->attribute}) {
            Storage::disk('s3')->delete($this->model->{$this->attribute});
        }
    }
}

I think it does what I need, however, this $this->model->{$this->attribute} bothers me. Any suggestions for S3Uploader overall?

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.