The Service Locator Design Pattern in PHP

The Service Locator Design Pattern in PHP Thumbnail image

The Service Locator Pattern is a common pattern in the PHP world, plus in other languages (most Java programmers are familiar with it). It is used by many PHP frameworks (such as the main Container class in Laravel).

To use a service locator, you need a few things. Firstly, you need to have some kind of 'service' (a class) that will type hint an interface. Then you need some form of a list (a registry) which maps interfaces to concrete classes. Then you tell the service locator that you need a class that implements some interface, and it returns back the relevant class.

Using a service locator, rather than just hard coding everything in, means that your code base is much easier to maintain, test and extend. You only need to write a new class that matches an interface, and you can easily set the service locator to use your new class. Despite service locators being common and used in many frameworks, they aren't always a great pattern to follow. They do help with dependency injection (and help for testing/maintaining/extending), but they also breaks the Dependency Inversion principle (from the SOLID principles)

webdevetc profile pic
webdevetc

I am a 29 year old freelance backend web developer from London, mostly focusing on PHP and Laravel lately. This is my site - I mostly write about PHP here. Contact me here (especially for any contracting jobs early 2019 in London ;) ).

Leave a Comment