mardi 9 août 2016

Improve oop designs with real example (file services)

I'm watching Uncle Bob to improve code maintainability and readability.

I've built a system in which can upload various file formats. Bellow I've posted the pdf one.

The below code works perfect but I need help if there is a way to improve code design and quality.

I use an abstract class FileServices:

abstract class FileServices
{
    protected $file;
    protected $fileName;

    public function __construct($file)
    {
        $this->file = $file;
        $this->fileName = pathinfo($this->file->getClientOriginalName(), PATHINFO_FILENAME);
        $this->setNewFileNameIfExist();
        $this->saveToDB();
        $this->saveToServer();
    }

    public function saveToServer()
    {
        $path = $this->path;
        $realNameWithExtension = $this->fileName  . $this->fileExtension;
        Storage::put($path . $realNameWithExtension, File::get($this->file));
    }

    abstract function saveToDB();
    abstract function setNewFileNameIfExist();
}

And PDF child class:

class PDF extends FileServices
{
    protected $fileExtension = '.pdf';
    protected $path = 'public/pdf/';

    public function saveToDB()
    {
        $newFile = new \App\PDF();
        $newFile->title = $this->fileName . $this->fileExtension;
        $newFile->save();
    }

    public function setNewFileNameIfExist()
    {
        $counter = 0;
        $realName = $this->fileName;
        $allPDF = \App\PDF::all();
        foreach ($allPDF as $pdf) {
            if($pdf->title === $this->fileName . $this->fileExtension) {
                while($pdf->title === $this->fileName . $this->fileExtension) {
                    $this->fileName = $realName . '(' . $counter . ')';
                    $counter++;
                }
            }
        }
    }

}

In the client:

$file = $request->file('pdf');
new PDF($file);

Aucun commentaire:

Enregistrer un commentaire