Service Layer in MVC

December 28, 2009

At one of the sessions that I attended at ZendCon I was introduced to the “Service Layer” pattern by Matthew Weier O’Phinney. At the time I didn’t quite get it but I’ve been trying out all those stuff that I’ve been meaning to while on vacation. There are a lot of resources on the web that explains the service layer. A good introduction from the PHP perspective can be found on Juozas’ website but I also like the analogy used here. Between all that I’ve read I realize that this is something that I’ve needed for a while and wish I had leveraged it  a bit sooner. Because the service layer for all intent and purposes sits between the controllers and the models there are a great deal of derived benefits:

  1. Swapping  out data sources is easier. The controllers no longer need to know any thing about the models just the api needed to access data from the service. That service could go from leveraging models that access a local database or an api used to interact with external data.
  2. Because the models are out of site from the controllers it becomes easier to upgrade or change the model layer with out too much adverse effect on the business logic (e.g. I’d like to upgrade a bunch of projects to doctrine)
  3. Services are more portable. Currently I leverage a restrictive MVC pattern where “user” functionality goes through a UserController which in turn leverages a table gateway patter that is made up of a Users class (the gateway) and User (row class). This works out great for code generation but inconvenient to work with in a large application because the functionality is so siloed.
  4. Exposing an api for 3rd parties to leverage is a bit more straightforward.

So I’m sold on the Service Layer concept now to get it hooked into my Zend Framework setup. We’ll check that out in the next post

Leave a Reply