mardi 11 décembre 2018

Laravel - Avoiding code duplication in models

I have a method for save some files in my models and I don't wanna duplicate it anymore, which is the best way to avoid this code duplication in Laravel?

You can see bellow some examples of the duplication, there it is the Product and the Articles Models, both have the saveFile method.

How can I isolate this code and reuse it?

// App/Article.php
class Product extends Model {
    protected static $storageFolders = "public/products";

    public static function saveFile($file, Array $options = []) {
        $filename = "";
        if (isset($options["name"])) {
            $filename .= $options["name"];
        }
        if ($options["unique"]) {
            $filename .= "-" . time();
        }
        $picture_path = "";
        if ($filename) {
            $extension = $file->getClientOriginalExtension();
            $filename .= ".$extension";
            $picture_path = $file->storeAs(SELF::$storageFolders, $filename);
        } else {
            $picture_path = $file->store(SELF::$storageFolders);
        }
        $storage_url = Storage::url($picture_path);
        return $storage_url;
    }
}

// App/Article.php
class Article extends Model {
    protected static $storageFolders = "public/articles";

    public static function saveFile($file, Array $options = []) {
        $filename = "";
        if (isset($options["name"])) {
            $filename .= $options["name"];
        }
        if ($options["unique"]) {
            $filename .= "-" . time();
        }
        $picture_path = "";
        if ($filename) {
            $extension = $file->getClientOriginalExtension();
            $filename .= ".$extension";
            $picture_path = $file->storeAs(SELF::$storageFolders, $filename);
        } else {
            $picture_path = $file->store(SELF::$storageFolders);
        }
        $storage_url = Storage::url($picture_path);
        return $storage_url;
    }

}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire