HTML5 Zone is brought to you in partnership with:

Rob Allen has been programming with PHP since 1999 and is a member of the PHP community. He is the lead author of Zend Framework in Action and is a contributor to Zend Framework, developing the Zend_Config component. Rob holds a Masters degree in Electronic Engineering from the University of Birmingham in the UK and is the Technical Director of Big Room Internet in the UK, focussing on project management and the company’s future technologies. Rob is a DZone MVB and is not an employee of DZone and has posted 29 posts at DZone. You can read more from them at their website. View Full User Profile

Objects in the model layer

03.24.2013
| 1304 views |
  • submit to reddit

I currently use a very simple set of core objects within my model layer: entities, mappers and service objects.

Entities are objects that represent something in my business logic. For example, in my traditional Album's tutorial, the entity would be the object that holds one album. It has properties such as title, artist and date created and methods that are specific to this entity.

Mappers know how to save and load an entity from the data store. This could be a database or a web service or an CSV file on disk. There is no requirement that a given entity maps to a single database table (or file on disk) as the mapper can simply use multiple tables for different properties within the entity if it wants to. The entity has no knowledge of how it is loaded and saved. This isolation means that I can have multiple mappers for the same entity that store it to different data stores.

Service objects provide the API that the rest of the application uses. I allow controllers and view helpers to talk to service objects, though I appreciate that others have a different take on MVC. Any given service object knows about mappers and entities and anything else that the business logic requires. I like having a service object as I can rework which mappers do what without having to touch the rest of the application. The service layer also know about other app details such as sending emails after a form is submitted. In an event based system, such as a ZF2, these details can now live in their own objects which listen for events triggered by the service object.

I dislike the phrase "service object" as the word "service" means so many things to so many people. I haven't heard a better phrase yet that everyone understands though.



Published at DZone with permission of Rob Allen, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)