Skip to main content

In PHP-DI, you can define a new service for an existing container without modifying the existing code (adhering to OCP). Here's how you can do it:

  1. Get the Existing Container: First, you'll need to have access to the existing container. If you've already got that, great!

  2. Define the New Service: You can use the set method to define a new service. Here's an example:

    $container->set('newService', function () {
        return new NewService();
    });
    
  3. Use the New Service: Once the service is defined, you can retrieve it from the container like any other service:

    $newService = $container->get('newService');
    

Remember, keep it clean and simple (KISS). If the new service has dependencies, make sure they are properly injected, and the code is organised to maintain a clear separation of concerns.