Command Pattern: A different way to organize your Service layer

Ujjwal Ojha
DevCupBoard
Published in
2 min readDec 20, 2017

If you are like me, you probably create a Service layer where your application’s business logic resides. And, if you are like most of PHP developers, you probably create service classes like this:

Now, you have decided to add Post liking feature to your application. Now, you add a new method to your PostService class.

So, it works and doesn’t look a mess at all.

But, what if you decide to add comments features and now, you have to add more methods to the PostService. This becomes unmaintainable if we keep on adding more methods to the class.

One way to organize it is to use Command Pattern. It consists of:

  1. A command object for each action
  2. A handler for each action which requires the command object as it’s argument

Command

Handler

Now, we need to call the handler and pass the command object as it’s argument. The responsibility of handing over command to handlers is done by a special kind of object called command bus.

Tactician library provides a really awesome command bus which does all the hard work of handling over command to its specific handler object.

You can head over to it’s awesome documentation to learn more about it.

If you like the post and want to follow us, you can follow us on medium and our twitter handler isdevcupboard as well.

--

--

Ujjwal Ojha
DevCupBoard

Software Developer, passionate LFC fan and a cricket lover!