Additionally/Accessibility/Container and services/Overriding a standard service

Overriding the Default Service

Fetching a default service from the container can be modified by adding your own service with a similar interface to the user container. You need to create a new service and return it from the 'getSingleton' method of the App\Bootstrap\ContainerFactory class before selecting from the default services. In the HLEB2 framework, each built-in service uses two identical interfaces (for different naming options), and you must return your own service as a singleton for the interface ending with 'Interface'. For example, for the caching service, it would be 'Hleb\Reference\CacheInterface'.

<?php
// File /app/Bootstrap/ContainerFactory.php

namespace App\Bootstrap;

use 
Hleb\Constructor\Containers\BaseContainerFactory;
use 
Hleb\Reference\CacheInterface;

final class 
ContainerFactory extends BaseContainerFactory
{
    public static function 
getSingleton(string $id): mixed
    
{
        
self::has($id) or self::$singletons[$id] = match ($id) {
            
// Adding a replacement for a service.
            
CacheInterface::class => new OtherCacheService(),

            
// ... //
            
default => null
        
};
        return 
self::$singletons[$id];
    }

    public static function 
rollback(): void
    
{
        
// ... //
    
}
}

The example shows how to replace the default caching service with your own. Here, it could be caching with database storage instead of file-based (default).

Similarly, you can "remove" a default service from the container by overriding it with a NULL value. But first, you must ensure that the service is not used in either the framework's own code or the application's code.

Page translated: chatgpt 4-o
Back to top