Sobes.tech
Middle+

What is a service locator?

sobes.tech AI

Answer from AI

Service locator is a design pattern that provides a centralized registry (or register) of services or dependencies of an application. It allows objects to access the required services without needing to know where or how these services were created. Essentially, it is a catalog of available services.

Main components:

  • Registry (Registry / Container): A storage where services are registered, usually by a unique identifier (name or type).
  • Locator: A method or object that allows requesting a service from the registry using its identifier.

Advantages:

  • Simplifies access to services, especially in large applications.
  • Reduces coupling between classes, as they depend on the locator rather than directly on specific service implementations.

Disadvantages:

  • Can hide class dependencies, making testing and understanding the code more difficult.
  • Violates the Dependency Inversion Principle (IoC), as the class itself "requests" its dependencies rather than receiving them from outside (as in dependency injection).

Example of a simple implementation:

<?php

class ServiceLocator
{
    private array $services = [];

    public function register(string $id, object $service): void
    {
        $this->services[$id] = $service;
    }

    public function get(string $id): ?object
    {
        return $this->services[$id] ?? null;
    }
}

// Example usage
class DatabaseService
{
    // ...
}

$locator = new ServiceLocator();
$dbService = new DatabaseService();
$locator->register('db', $dbService);

// Somewhere else in the application
$db = $locator->get('db');
// ... use $db

Service locator is often implemented as a singleton to ensure global access, although this adds its own drawbacks (global state).

In modern PHP applications, dependency injection is more commonly used as a preferable alternative, as it makes dependencies more explicit and simplifies testing. However, a service locator can be useful in certain scenarios, such as lazy loading of services or integration with legacy code.

What is a service locator? — PHP - sobes.tech