views:

75

answers:

2

Hi

I have some PHP classes I am creating from XML config. What I would like to know is this:

Am I better off (from an object-oriented standpoint) having factory methods to create those classes from XML or passing in XML to the constructor to create the classes?

The factory approach has the advantage of separating construction from usage and more easily allowing alternative implementations but you then need to expose setters or pass in a whole bunch of objects to the constructor that constitute it's state.

A further subtlety of this is that passing in the XML allows you to create the objects top down and some lower down objects will need references to those objects above them. The second method will result in something that's more bottom up.

Or is there some more design pattern type way of going about this?

Thoughts?

+1  A: 

Sounds like you need a some sort of dependency injection framework. There is an excellent outline of Symphony's DI here. A good DI framework will help you design a clean and testable architecture which can alleviate issues like constructors needing too many arguments.

rojoca
+1  A: 

For a clean design it would be best to keep the code for creating a Foo from XML outside of Foo completely, but in some kind of factory. That way, Foo can stay the same if you want to add a way to create it from JSON, CSV or whatever data too.

Bart van Heukelom