M
M
Moshiwa2021-02-13 20:02:33
Design patterns
Moshiwa, 2021-02-13 20:02:33

How to implement saving data using the factory method pattern?

Do I understand correctly that it is necessary to create an interface with a save method and several classes (saving to a database, saving to a file) that implement it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alvvi, 2021-02-13
@Moshiwa

Laravel has little to do with it. The pattern can be applied anywhere.

abstract class Presister
{
    abstract public function factoryMethod(): Post;

    public function save(): void
    {
        $post = $this->factoryMethod();
        // сюда логику сохранения
        $post->save();
    }
}

class FancyPostPresister extends Presister
{
    public function factoryMethod(): Post
    {
        return new FancyPost();
    }
}

class RegularPostPresister extends Presister
{
    public function factoryMethod(): Post
    {
        return new RegularPost();
    }
}

interface Post
{
    public function save(): void;
}

This is how the pattern might look in the save context. The main task of this particular pattern is not to abstract the way data is stored, but to abstract the very process of creating objects with similar interfaces. However, nothing prevents you from making another Presister with a different save method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question