views:

44

answers:

2

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?

+1  A: 

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.

Michael Venable
A: 

What you're describing is an implementation of a Data Access Layer - it doesn't sound like an example of the Factory Method pattern, nor the Abstract Factory pattern.

Yes, ORMs bridge the gap from objects to relational databases, and can serve as your Data Access Layer. Bear in mind, any ORM you use has certain pros/cons/limitations. Depending on your experience and requirements, writing your own data access layer is sometimes a good idea; don't feel like you HAVE to use a 3rd-party ORM.

Yes, a good data access layer makes it easy to swap out your storage mechanism (different database, XML, flat files, whatever) without changing your business logic, UI, or other code.

Regardless of loose-typed or strong-typed languages, if you're working in an OO language, it will be much easier to write code using data objects (provided by an ORM or homegrown data access layer). I'm sure it's possible to write a system with no data access layer, where your business layer works directly with the database. But it will likely be more challenging to implement and maintain.

mikemanne