Dependency Inversion and Interface Segregation using Laravel’s Service Container

In very short, we’re going to cover the Interface Segregation Principle (ISP) and the Dependency Inversion Principle (DIP) in this article, and practically how we implement them within a Laravel environment.

Dependency Inversion Principle

  1. The principle is handy for the decoupling modules (making them independent of one another)
  2. Modules should not depend upon each other, but instead upon abstractions (in PHP there are generally interfaces)
  3. Abstractions should not be concerned with the implementation of functionality

Interface Segregation Principle

The next part we’re going to look at in this article is the Interface Segregation Principle, roughly covered in these two points

  1. No client should be forced to depend upon methods which it does not use
  2. Many specific interfaces are better than a single general purpose interface

Approaching the task

Now that we have recapped the principles, very briefly, here’s how we implement this.

  1. Split the required functionality into any parts which, according to the Single Responsibility Principle, would need to be separate – this will create interface segregation
  2. Understand the communication between any of these parts at its most generic level
  3. Create the interfaces (abstractions) through which this communication can be achieved
  4. Inject your dependencies based on the abstractions, achieving dependency inversion
  5. Resolve the abstractions to concretions with the Laravel service container

Implementing the Approach

The specification I was working to was (roughly);

Players should be able to send cash, bullets, and bonds to one another

Paraphrased specification

I’m going to quote some code below, which comes from this Pull Request

1. Split the requirements into single responsibilities

Several things happen when funds are transferred between accounts, so we need to logically split these

  1. Currency is credited to a character
  2. Currency is debited from a character
  3. A log of the transaction is stored
  4. A notification is sent

Logically, only the first 3 parts of this need to be programmed, because we can use Laravel Events, Listeners, and Notifications to handle the forth part.

Part 1 and 2 of this can be handled through a single class, which is responsible for the adjustment of currency amounts on a specific character.

So that leaves part 3, and the wrapping of parts 1 and 2 for our transferrer. With this separation, I now have 2 classes with single responsibilities:

  1. CurrencyHandler which is responsible for handling currency on characters (checking, crediting, debiting), single responsibility: this class will only change if the way in which we store/calculate currency is changed
  2. CurrencyTransferrer which is responsible for tying up the process of transferring currency from one character to another, single responsibility: this class will only change if the way which we carry out a transfer of currency changes

2. Understand the required communication

The transferrer depends upon the handler, because the transfer cannot happen without the handler. The next question is; what does the handler need to be able to communicate (whether answering questions, or receiving instructions)?

  1. Question: Is this (string) a valid currency? We have three in game
  2. Question: Is this amount valid for this character? i.e. can they afford to expend this amount
  3. Instruction: Add X amount of Y currency to this character
  4. Instruction: Remove X amount of Y currency from this character

And we also have to think about the transferrer, what do we need to be able to communicate with a currency transferrer?

  1. Instruction: Transfer X amount of Y currency from A character to B character

3. Create the Interfaces

From these single responsibilities, we can create 2 interfaces

  1. HandlesCurrency
  2. TransfersCurrency

HandlesCurrency defines the following methods to be implemented, according to the lines of communication we defined

public function creditCurrency(Character $character, string $currency, int $amount): void;

public function debitCurrency(Character $character, string $currency, int $amount): void;

public function characterHasOnHand(Character $character, string $currency, int $amount): bool;

public function validateCurrency(string $currency): bool;

Whereas, based on the required communication, the TransfersCurrency interface declares the following

public function transfer(Character $from, Character $to, string $currency, int $amount);

4. Segregate these interfaces from their concretions, and inject the abstractions

Laravel makes this bit exceptionally easy… (the following is within a Service Provider)

$this->app->bind(HandlesCurrency::class, CurrencyHandler::class);
$this->app->bind(TransfersCurrency::class, function () {
    return new CurrencyTransferrer(
        resolve(HandlesCurrency::class)
    );
});

So what we are doing here is…

  1. When I request the HandlesCurrency interface, Laravel will give me an instance of the CurrencyHandler class (concretion)
  2. When I request the TransfersCurrency interface, Laravel will give me an instance of CurrencyTransferrer
  3. The constructor method of CurrencyTransferrer requires an injection of its dependency of HandlesCurrency so what we do, is we tell Laravel to inject the appropriate resolution of HandlesCurrency (which is the CurrencyHandler) in for us
  4. Now, whenever we want to transfer currency between players we can simply request a CurrencyTransferrer

There are some really important things to note here;

  1. The CurrencyTransferrer does not know, nor care, how currency is handled throughout the game, it just knows that it needs to be able to ask some questions, and issue some instructions to the implementation
  2. Nowhere in the codebase (unit tests excluded) will the CurrencyHandler or the CurrencyTransferrer be mentioned, any implementation will only ever depend upon the abstractions thus, if I were to want to completely replace the CurrencyHandler, because it’s now handled by a microservice (for example), I would create a class that implements the interface, and change the service binding, every usage would be swapped

Just to wrap this full circle, let’s assume we have an API end point which transfers funds from one character to another, when we declare our Controller we would define the constructor something like as below (and Laravel would do the rest for us)

class CurrencyTransferController extends Controller
{
    protected $transferrer;
    public function __construct(TransfersCurrency $transferrer)
    {
        $this->transferrer = $transferrer;
    }
}

In Summary

To summarise here, what we’ve done is taken a piece of functionality which could’ve gotten very messy. We have split it into its reusable components, we have then inverted any dependency on those concretions, so we only depend upon the channels of communication which they have.

After doing all that we have completely interchangeable classes, we’ve used the Laravel service container, to understand how to resolve (and inject a dependency into a concretion of) our abstractions.

This is a very simple example, but what it does is demonstrate how to create highly decoupled code, following the I and the D from the SOLID principles.

Some disclaimers

  1. The Character model is injected directly, and is not inverted via an interface. I am porting old functionality across, and nothing throughout the system can function with the concept, however I think I probably will go and implement an interface to the effect of HasCurrency rather than accessing the fields directly. The other thing is, if I’m not careful I create lasagne here, I may, later on, decide to implement the HandlesCurrency interface directly upon the Character model, but in doing that I will be breaking the Single Responsibility Principle – I’m still toying with the different ways I could do this
  2. Strictly speaking the CurrencyHandler could be split into CreditsCurrency and DebitsCurrency – the reason I haven’t done this is because they are direct opposite functionalities. But now that I have noticed this, I may well go and change it
  3. I’m not perfect – there will be mistakes, I’m okay with that, but feel free to flag them, I am always happy to take on board other perspectives and learnings

Laravel Deep Dive – Mafia Online – Contents
I will update this as I add new articles

  1. Introduction
  2. Dependency Inversion and Interface Segregation using Laravel’s Service Container
  3. Achieving Single Responsibility with HTTP Requests in Laravel (coming soon)

Beware, the Anti Pattern!

In this article I am going to cover the application of patterns within your… application. In short, I am going to show you how to use design patterns in a logical manner.

Patterns are always sometimes awesome!

The first thing here is that all design patterns have a purpose, every design pattern has its place. Whilst I’m talking about design patterns the same can be said of development methodologies, database designs, and really any other kind of concept.

The proper application of design patterns can take a frustrating piece of software, and make it easy to maintain, or hyper-secure, or crazy performant.

The bad application of a design pattern will do the exact opposite.

But, why would you ever not use a pattern?

Well, when it’s not the right time to use it. Every pattern has its place, but not every pattern should be used everywhere, it’s a bad idea.

Don’t take my word for it, let’s look at some practical examples and experiences that really demonstrate what I am saying here.

I’m going to be deliberately controversial here, and I’m going to pick stuff that all developers seem to love and then prove where it will ruin your application.

I’ve heard of Patterns, what is an Anti Pattern?

An anti-pattern is a pattern. Subjectively an anti-pattern is when you take a pattern and either apply it in the wrong circumstances, or implement it badly.

The consequence of the application of an, otherwise great, pattern, causes adverse impacts (usually for maintainability, or for performance etc). Now, it is an anti-pattern.

Model View Controller (MVC)

Well all love MVC, right? I mean, what’s not to love? CodeIgniter, CakePHP, Laravel, Angular, and Joomla all follow this pattern. It is arguably one of the most used design patterns of recent times.

For good reason, it’s awesome! Because it’s awesome, developers are pretty darn impassioned about using it everywhere, and they are right, in the vast majority of cases.

So when, I hear you ask, would this not be a good idea? When could it be an anti-pattern?

What about if I am writing a daemon, which is going to continuously monitor the usage of the mounted hard drives on a server and, in certain scenarios, send an email to a system administrator?

Don’t need models – we’re not handling any data. We don’t have anything, not even a CLI output, so no need for views. Realistically there’s not a controller it’s a standalone script. MVC would be a bit overkill, in this instance, wouldn’t it?

That’s a bit of a drastic example though, let’s look at something more subtle.

Single Responsibility Principle

Ah, right. Let’s get controversial then, shall we?

A class should only have one reason to change

Single Responsibility Principle, SOLID Principles

Everyone loves this, and likes to really preach about it. It is crazy controversial, widely adopted, and I personally think that it’s a good idea.

The Single Responsibility Principle is like the best song in the world, that you hear 1,000 times per day on every music channel and radio station. It is best practice, yes. But sometimes, it’s okay to break it!

Oh Gosh, quick, get the smelling salts and a wet flannel, they’ve feinted!

The whole point of the SOLID principles are to make well structured, easy to maintain code.

So, time for a real-life example. I have a class, it is an Eloquent Model. It is responsible for some mission-critical, core functionality. This class has a method within it. This method is 150 lines long (probably 50 lines of code, once you take out empty lines and code comments).

This method, in of itself, could (and maybe even should) be abstracted into it’s own class. For some context it is a static method, responsible for fetching records, based on a set of arguments.

Every part of the Single Responsibility Principle dictates this method should be abstracted to its own class, perhaps even a set of classes.

Internally, I have had this code reviewed, and to quote the developers who have checked (and indeed worked on) it, it is “exceptionally easy to follow” and “super easy to add and change the functionality”.

It is, essentially, a set of if statements. Based on the outcome of those if statements, the Eloquent Query is modified, then returning either limited, or paginated, results.

So, I hear you scream, “why won’t you abstract it?!” – well I could. But following conversations with the development team, the code would actually be harder to follow if I were to abstract and refactor it.

In this instance, the code can be easily found, easily changed, and is incredibly stable.

Following Single Responsibility to the letter, this time, would be an anti-pattern. Rather than making life easier, it would make life more difficult. Abstraction can be bad! If it has no performance, functional, or security perks. It makes the code more difficult to maintain and follow; then abstracting it would not make any sense. Except to follow a pattern for the sake of following a pattern, at this point, it becomes an anti-pattern.

Dependency Injection

Oh God. I’ve been here before. It is bad. I remember the flames, vividly. As the Reddit Hellfire engulfed my computer. Just kidding, but this one does really evoke emotional reactions.

Just quickly and very simply, dependency injection is parsing an object (dependency) into another object on which the latter depends. Thus, injecting the dependency. It usually looks (forgetting containers and autowiring) something like this.

class Calculator{

public function __construct(
AdditionServiceProvider $addition,
SubtractionServiceProvider $subtraction
){
$this->additionService = $addition;
$this->subtractionService = $subtraction;
}
}

The point here is that I can control the services that the Calculator is using. So if I were, at a later date, wanting to swap out my AdditionServiceProvider for AcmeIncAdditionServiceProvider (assuming they implement the same interface, or extend the same base class) then I could, and the rest of the class would work as expected.

However, I have, several times, seen things like this.

class PaymentsIncorporatedWrapper{

public function __construct(
PaymentsInc\Payer $payer,
PaymentsInc\Refunder $refunder
){
$this->payer = $payer;
$this->refunder = $refunder;
}

}

Right, this makes sense, doesn’t it? Wire up the payer and the refunder, then drop them into your Wrapper. As I said above, take the dependency injection container side of it; whenever I want to do something with the PaymentsIncorporatedWrapper I have to do something like

$payer = new PaymentsInc\Payer($apiKey, $somethingElse);
$refunder = new PaymentsInc\Refunder($apiKey, $somethingElse);
$wrapper = new PaymentsIncorporatedWrapper($payer, $refunder);

That’s a kind of annoying amount of code to write, to instantiate a class. “But the container does that for you!” I hear you scream. Yes, yes it will.

But why? You don’t know, at the time of instantiation, that I need the refunder. I might just be querying a payment. Why do I need the refunder? I don’t. Ah, maybe this is an anti-pattern.

Also, this set of classes is specific to the PaymentsInc integration. So it’s not like I’m going to swap in another payment provider (otherwise this would all make sense).

In this instance, when I couldn’t possibly want to swap anything else in/out, perhaps this would make more sense?

class PaymentsIncFactory{

public static function getPayer() : PaymentsInc\Payer
{
$factory = new static();
return $factory->getPayer();
}

private function getApiKey() : string
{ ... }

private function getSomethingElse() : string
{ ... }

public function getPayer() : PaymentsInc\Payer
{ ... }

...

}

class PaymentsIncoporatedWrapper{

public function takePayment(float $amount)
{
$payer = PaymentsIncFactory::getPayer();
$payer->takePayment($amount);
}

}

Anybody who is passionate about Dependency Injection will argue this is wrong, and they will probably cite Unit Testing as the reason. But, to my knowledge, unit testing isn’t justification for using Dependency Injection.

In fact, I have implemented both Unit Testing, and Test Driven Development, without unnecessarily using Dependency Injection. Of course, Dependency Injection was used, just only where it was truly necessary.

And the point of those tales was….

Just because a pattern is the best thing since sliced bread, doesn’t mean you should apply it liberally, everywhere, without thinking about it.

In the above I’ve taken three of the most beloved patterns we possess, and given you three good places where perhaps those pattern were best not applied.

So think about the patterns you’re using, never blindly use it because someone on [insert social website or influencer here] said is is amazing.

The key, as with all things, is to genuinely understand the pattern, its application, its benefits, and its constraints. And then think, and make a decision, about whether it makes sense to apply it in your use case.

Further Reading / Sources

  1. Model View Controller (MVC) – Wikipedia
  2. Single Responsibility Principle – Wikipedia
  3. Dependency Injection – Wikipedia

How Eloquent breaks the Single Responsibility Principle, and why I’m okay with it

Hi everyone

I thought I would discuss a controversial one today, in order to give an articulated response to a common argument about Eloquent (and generally the Active Record pattern)

Firstly, just in case you don’t know, here are some definitions:

Single Responsibility PrincipleThe “S” in the “SOLID” principles. In short, this means one class should have one job. The idea is to keep your code modular and easy to switch out.

SOLID Principles: I’ll do an article on this one day, but it’s a discussion for another time. Like all principles or methodologies they’re like the Pirate’s Code, they’re more like guidelines than hard and fast rules of software design.

Eloquent: Is an ORM (object relational model) which comes as standard with Laravel, and is absolutely fantastic

Active Record: Is a design pattern whereby a record from a database table is returned as an object that can be manipulated and can update the database as part of its role. Usually this means you can do something like

$myRecord = RecordFactoryOrSomething::getTheRecord();
$myRecord->field = 'Updated Value';
$myRecord->save();

This is quite handy for programming as you can store all of the logic to do with saving in the Model.

Laravel: Is a framework for Rapid Application Development, which, like Eloquent, is amazing. It basically gives you all of the tools you need to build bespoke software, but in a way that means you can do it at lightening speed, with crazy accuracy. I can’t sell Laravel well enough, honestly it’s amazing.

So, now that the introductions are out of the way; the Single Responsibility Principle isn’t mandatory

I’d like to make my first point, which quite simply is: The Single Responsibility Principle is a principle. I joked earlier about principles being like the Pirate’s Code, but one does have to be careful when using design patterns and principles, if we’re not careful they become anti-patterns which essentially means their over usage and religious subscription actually causes more problems in the software than it would’ve done had it have been omitted completely.

All patterns should be used in a way which makes sense and makes the code more efficient and maintainable. Ultimately maintainable code which is easy to extend is cheaper for the business whose employing you. Or means your profit margin is higher if you’re running your own business, freelancing or contracting.

Single Responsibility is pretty subjective

This is another slight issue I have with the Single Responsibility Principle. I actually love the principle itself. It makes sense, separate things into logical blocks, and if each class has its own responsibility (and only the one) then it’s quite easy to find how the classes are supposed to work together, perfick.

However, a single responsibility has to be defined. If you defined the single responsibility of a class as “do the business logic” then you could have a God class, which technically has a single responsibility. That would, obviously be a bad usage.

So, let’s look at the other end of the spectrum and go into tiny, tiny detail. Do I need a class for executing SQL queries, and one for generating them? Maybe that means I need a class which prepares INSERT statements, another for UPDATE, and so on and so forth.

The latter approach to single responsibility is most definitely an anti-pattern. That level of abstraction and obscurification will only ever be bad for managing and debugging code.

So then how does the Eloquent Model break it?

The big problem people have with Eloquent is that the Model class fulfils multiple responsibilities. You can’t really say “it is responsible for interacting with a specific table” because it is also representational of a record.

That means it has, at least, two responsibilities: Executing queries against a table, and representing a record. The power of the Eloquent Model is that it actually does more than that, it also defines relationships etc.

So, let’s be honest, it rips the Single Responsibility Principle apart, but I’m totally okay with that.

But, if you love SRP, how can you like the Eloquent Model, you heathen?

The reason I love it, is because what you actually do is group those few responsibilities in an entirely sensical and logical place, you end up with a class which can give you lots of information; all of those responsibilities can be so beautifully wrapped; as so you end up with something like this:

NB: I’ve omitted a lot of code here, just to demonstrate my point I didn’t need it

class User extends Model
{

    // This is a query run against the table
    public static function findUserOnEmail($emailAddress){}

    // This is an action (probably running a query)
    public function changeUserLevel($userLevelId){}

    // This is a relationship defined
    public function friends()
    {
        return $this->hasMany('\ModelNamespace\Friendship');
    }

}

And there you have it, in a few lines of code we have some functionality we need on the table to complete search functionality which has to otherwise be stored somewhere else, that usually doesn’t make sense.

You’ve got an action that can be publicly exposed to other developers to carry out a task without any prior knowledge of the data architecture of your system or how the user levels.

And you’ve got an easy way to get all of the friends for that user.

This is why I love Eloquent. Because it puts aside rules and methodologies for a logical and sensical reason, in order to provide an exceptionally transparent way to manage your data layer.

But wait, there’s more!

All of this is without things like the hookable functions so you can do certain functionality (think expire memcached objects, etc) based on creation, update, or save. There’s a huge amount of functionality built in, and it’s perfect for almost everything.

I’ll be honest, all ORMs fall down with certain complex queries – but it’s not supposed to tackle that problem. It’s the vast majority of monotonous tables and relationships which have to be constantly created to support any kind of enterprise software which becomes so much faster.

Alright, so what’s the alternative?

The alternative to this, realistically, is the Service-Mapper-Entity pattern. In short this means each table has an Entity responsible for representing the data. You then have a Mapper responsible for executing SQL, and then you have a Service which is the interface exposed to the rest of the application. So you tell your service to do something, and it does this using the Mapper, usually returning Entities.

Personally, that feels like too much code to do a simple task. And it is just a personal opinion and there are times that this is very useful, the thing that makes me really sway from that is that when I create 5 tables, with, let’s say 3 bridging tables to support many-to-many relationships; I suddenly can end up with 8 sets of Service, Mappers and Entities. This is 24 classes, which is a lot, compared to 8 classes; which define their relationships and are ready to be used with hydration and all of that stuff.

So, it’s okay to break the Single Responsibility Principle?

Before I ignite an absolute flame war, which this particular topic has the potential to do. In a word, yes. But only if you have a good reason, and you’ve done it to make your code maintainable, readable and easy to manage; without sacrificing security or anything like that.

In this particular instance, I think breaking the principle is fine. It makes sense, and it makes for, even on large scale applications with a large data layer, an easy way of managing this data layer and managing it in a way which is sustainable moving forward.

And how do I keep it clean?

For me personally, follow two major rules.

  1. Static methods do something to the table itself – this could be searching, filtering, retrieving, etc.
  2. Methods on the class, do something to the record – I often like to wrap common functionality in a method, it makes it easily accessible to everyone else

For example; let’s say we activate a user account, there are two ways of approaching this:

// Fetch the record with ID of 17
$record = User::find(17);

// Set the is_user_active field to 1
$record->is_user_active = 1;

// Save this record
$record->save();

There isn’t necessarily anything wrong with this. Until I want to hook into that functionality, or I change something else, let’s say I nullify the activation_key field, for example. Then I would have to go and find everywhere I’ve done this. I don’t like this, it’s a bit awkward.

So I prefer to do something like this

// Fetch the record with ID of 17
$record = User::find(17);

// Activate the record
$record->activate();

// Within your User model class
public function activate()
{
    $this->is_user_active = 1;
    $this->save();
}

Disclaimer: You can do this using the updated method on in Eloquent, so you could hook into this and check to see if the is_user_active field has changed and then hook in that way; word of caution with that though – you can end up with a hell of a lot of if statements and it can get quite messy.

In summary, Eloquent is awesome

  1. It let’s you have an easy to manage data layer for your application
  2. The Model class does break the Single Responsibility Principle, but it can be argued that Model class is responsible for representing and interacting with a single table
  3. You end up with easy to plug into user-land code
  4. You can manage your relationships beautifully

So really, when weighing that up I can’t see any reason not to use it. It’s extendible (I’ve extended the base Eloquent Model multiple times, with a lot of success), you can overwrite functionality where you want to really easy – though you don’t often need to, because the functions you can plug into are so useful.

As always I’d be really interested to hear any thoughts you guys have on this, especially as I know it’s a bit of a controversial one!