Search code examples
symfonyrepository-pattern

How to build a Symfony Repository from scratch?


I'd like to build a Symfony application without a database. But I do like the Repository/Entity pattern that is (usually) provided by doctrine. So I'd like to build my own repository service and entity classes.

For background, in this application the repository is a directory on a file system, and all the entities it provides are (defined by) directories inside that directory. But for the sake of argument, the repository might as well be an email inbox, and the entities emails, or an XML file, and the entities XML fragments.

How do I go about building such a repository? I could simply write a custom service and entity classes, but should I 'register' that repository as a Service in Symfony, if so, how and why? Should I extend or implement Symfony classes or interfaces?

Or, are there any such examples around?


Solution

  • A repository is just a design pattern. It is build to isolates the data from your application.

    Don't think everything can be a repository, just because you can fetch a list of results or a singular result in general. For example, in a filesystem you have permissions as additional dimension. In an email you have mail headers, protocol, server behaviour, etc.

    Usually for these use-cases there are other abstraction libraries. For example for using files on all different types of filesystems (local, ftp, nfs, aws s3, dropbox, ceph, webdav, etc.).

    You can design a repository pattern service around these libraries. Keep in mind that a repository pattern abstracts query'ing your data, so you need some query mechanism for your storage driver(s). For example when using a filesystem you might need to use grep in case you want to search in the content. Or when using email you have to rely on what the protocol/server offers.

    In all cases you can index your sources by using elasticsearch for example and query that instead of the source itself.

    Doctrine's repository is just an abstract over the Doctrine querybuilder. Which you can build for anything you like.