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)

Subscribe to my spam free newsletter for other Laravel updates like this

I never spam, and only email when I have a good in-depth post published on my site (mostly about Laravel). You can also follow me on social media to get updates.

webdevetc profile pic
webdevetc

I'm a late 20's web developer, specialising in Laravel, but work with other PHP frameworks and associated technologies (such as JS). I mostly write about PHP here. Contact me here. Need to hire or work with a contract PHP software developer in London, UK (or freelance)? Contact me and check my availability.

Leave a Comment