How to implement the Service Locator design pattern in PHP for centralized object retrieval?

Member

by dana , in category: PHP General , 2 years ago

How to implement the Service Locator design pattern in PHP for centralized object retrieval?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , 2 years ago

@dana 

The Service Locator pattern is used to provide a centralized location for retrieving objects that are needed throughout an application. Here's a basic implementation in PHP:

  1. Create a service locator class:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class ServiceLocator {
  private $services = array();

  public function __construct() {
    // Instantiate any required services
    $this->services['db'] = new Database();
    $this->services['mailer'] = new Mailer();
  }

  public function getService($serviceName) {
    if (!isset($this->services[$serviceName])) {
      throw new Exception('Service not found: ' . $serviceName);
    }
    return $this->services[$serviceName];
  }
}


  1. Define your services:
1
2
3
4
5
6
7
class Database {
  // ...
}

class Mailer {
  // ...
}


  1. Retrieve services from the service locator:
1
2
3
$locator = new ServiceLocator();
$db = $locator->getService('db');
$mailer = $locator->getService('mailer');


By using the service locator pattern, you can easily retrieve any required objects from a centralized location. This can make your code more modular and easier to maintain, since you can easily swap out implementations of services without having to update every place in your code that uses them.