Search code examples
databasedesign-patternsobjectfactories

Object Factory Question - using database query information to create objects


I have several objects, like products, order, etc. When I get information from my database I take a row and create one of the types of objects. I then work with that object created. I read this is called a factory.

Is there some advantage to doing this? Especially in a loosely typed language like PHP?

Thanks

edit: is this where I get database agnosticity? Is this what an ORM essentially does?


Solution

  • By creating your objects from the database queries, you are defining the mapping between your objects and the relational database. This is exactly what ORM software does.

    By doing so and ensuring that your objects never directly access the database, but instead use your database-access functions/objects, you are protecting your code from changes in two ways:

    • Changes to your database schema will not ripple through your code. Instead, the code changes will be located only in your database access objects.

    • You can switch to a different DBMS by implementing a new database layer that follows the same interface as the original. Your other objects will not require changes.

    I guess in that sense, you gain some database-agnosticity, but you'll probably be better off using a database library that provides that agnosticity out of the box.

    In my opinion, the advantage is you are working with objects and gain all of the advantages that an object-oriented language offers. You can then read the domain logic at a higher level (in terms of the objects you have defined) without sifting through database queries. Writing the ORM yourself can be tough, but there are tools out there that help with that.

    This is the route I normally take, but I don't do any PHP development, so I can't say how well it applies to that language.