So I'm making this web application in PHP, and I wanted to make a decent model layer (as much as possible) with Domain Objects and Data Mappers, all orchestrated by Services.
And now I'm thinking, how should I create my objects?
But then:
DataMapper
usually. The others don't have set methods they need to implement; I don't want to rely on names, because naming conventions change).new
keyword?But then:
I don't know, that's why I'm asking! :P
What should I do? Is there a better approach to this?
Brian Vanderbusch's comment hints at the best way. You should use Dependency Injection to inject the mapper you need. However, to reduce coupling you should also type hint the most basic type, usually an interface.
How you actually inject the Data Mapper into your (presumably) model layer doesn't really matter. A Dependency Injection Container can store all the metadata about which classes need which data mappers and automatically inject the dependencies for you. However, without using a DIC, the top level of your code should, at the most basic level, look like this:
$model = new ProductsModel(new ProductsDataMapper(new Db('localhost', 'u', 'p', 'd')));
of course the mapper and database would almost certainly be shared between other objects in the real world and you'd pass in the references to the existing instances. If you need multiple mappers in the model layer, pass them all in as constructor arguments.
The key here is to build the entire object graph at the very top level of the application rather than worrying about locating them after the fact. This is the premise of inversion of control, which you can think of as building the structure from inside out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With