Documentation/Container/Services/Converter

Converting to PSR

To use external libraries that employ contracts based on PSR recommendations, you may need to convert your own framework entities into the appropriate PSR objects.

Due to the framework's principle of self-sufficiency and initial rejection of external dependencies, the framework's system classes are similar to standard ones, but have their own interface. To adhere to the standards, this is addressed by using the Converter adapter, implemented as a Service.

The Converter service provides methods to obtain objects according to PSR interfaces, derived from the system objects of the HLEB2 framework.

Methods of using Converter in controllers (and all classes inherited from Hleb\Base\Container) exemplified by retrieving an object for logging using PSR-3:

// variant 1
use Hleb\Reference\ConverterInterface;
$logger $this->container->get(ConverterInterface::class)->toPsr3Logger();

// variant 2
$logger $this->container->converter()->toPsr3Logger();

Example of retrieving a logger object from the Converter service within application code:

// variant 1
use Hleb\Static\Container;
use 
Hleb\Reference\ConverterInterface;
$logger Container::get(ConverterInterface::class)->toPsr3Logger();

// variant 2
use Hleb\Static\Converter;
$logger Converter::toPsr3Logger();

The Converter service can also be obtained through dependency injection via the interface Hleb\Reference\Interface\Converter.


#toPsr3Logger

The toPsr3Logger() method returns a logging object with the PSR-3 interface (Psr\Log\LoggerInterface).


#toPsr11Container

The toPsr11Container() method returns a container object with the PSR-11 interface (Psr\Container\ContainerInterface).


#toPsr16SimpleCache

The toPsr16SimpleCache() method returns a caching object with the PSR-16 interface (Psr\SimpleCache\CacheInterface).


#PSR-7 Objects

There are a sufficient number of third-party libraries for handling PSR-7 objects, so including another implementation in the framework is unnecessary. For example, they can be created using the popular Nyholm\Psr7 library:

use Hleb\Reference\RequestInterface;
use 
Hleb\Reference\ResponseInterface;
use 
Hleb\Static\Container;

// Request
$rq Container::get(RequestInterface::class);
$psr7Response = new \Nyholm\Psr7\Request(
    
$rq->getMethod(),
    (string)
$rq->getUri(),
    
$rq->getHeaders(),
    
$rq->getRawBody(),
    
$rq->getProtocolVersion(),
);

// Response
$rs Container::get(ResponseInterface::class);
$psr7Response = new \Nyholm\Psr7\Response(
    
$rs->getStatus(),
    
$rs->getHeaders(),
    
$rs->getBody(),
    
$rs->getVersion(),
    
$rs->getReason(),
);

The set of parameters in the constructor depends on the chosen library.
To avoid initializing this way each time, the implementation can be delegated to a separate class or service.

CSRF Protection Events

Page translated: chatgpt 4-o
Back to top