Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I create my Data Mappers/Domain Objects/Services?

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?

Factories?

But then:

  • I'd have to use reflection to actually enforce if an object implements a certain interface (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).
  • I'd have to defy the law of demeter by passing the factories into the ServiceFactory which would then only pass it to the service it creates.

The new keyword?

But then:

  • I'd have problems testing the code in isolation.
  • Feels too tightly coupled.

Anything else?

I don't know, that's why I'm asking! :P

What should I do? Is there a better approach to this?

like image 856
Madara's Ghost Avatar asked Oct 24 '13 16:10

Madara's Ghost


1 Answers

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.

like image 123
Tom B Avatar answered Nov 16 '22 05:11

Tom B