Search code examples
phplaravelooprepository-patternfactory-pattern

PHP design patterns Factories, Repositories and...?


We have factories for creating complex objects. (For makin' stuff)

We have repositories for find them. (For findin' stuff)

What do we have for updating them? (For changin' stuff up)


Seems like a missing piece in the puzzle? I don't think it belongs in repositories, as that breaks single responsibility...


Solution

  • Updating an Entity (and so, the database) belongs to the Repository. The Repository itself is an Layer between the Database itself and the program.

    Every Database Operation therefore belongs to the Repository. Also, a Repository mustn't communicate with a database, it also could have an XML, CSV or API as data source. But that doesn't matter, because you're communicating with the Repository. The Repository deals with all that's coming afterwards.

    You could just change the Repository with another one and your program would work without any problems, because the repositories all implement the same interface. You don't like that MySQL Database anymore, that old fashioned CSV is much better? Just replace the used Repository and you're done.

    Finding an entry with an repository isn't more than a SELECT statement, so why won't you UPDATE or DELETE with it?

    Further reading on the MSDN

    Found a great explanation and example on web.archive.org