What is PSR-11 standard?
The PSR-11 standard is a PHP-FIG (PHP Framework Interop Group) recommendation, officially titled “Container Interface”. It defines a common interface for dependency injection (DI) containers in PHP. This standard helps ensure interoperability between frameworks, libraries, and other components by providing a consistent way to retrieve objects or services from a container.
Key Features of PSR-11:
- Purpose:
It standardizes how objects or dependencies are fetched from a container, making it easier to swap or integrate DI containers. - Interface:
The standard defines a single interface:
namespace Psr\Container;
interface ContainerInterface
{
public function get(string $id);
public function has(string $id): bool;
}3. Methods:
get(string $id):
Retrieves an entry (object or service) from the container by its identifier. If the identifier does not exist, it should throw an exception.has(string $id): bool:
Checks if the container has an entry for the given identifier.
4.Exceptions: PSR-11 also defines two exception interfaces:
Psr\Container\NotFoundExceptionInterface:
Thrown when the requested entry is not found.Psr\Container\ContainerExceptionInterface:
Thrown when there is an error while retrieving the entry.
Why is PSR-11 Important?
- Interoperability:
Developers can switch between DI containers or integrate different frameworks/libraries seamlessly. - Standardized API:
Since all PSR-11-compliant containers implement the same interface, you don’t need to learn a new API for each container. - Easier Testing:
You can use the same approach to mock or test dependency injection containers across different systems.
Example Usage:
Here’s how a PSR-11-compliant container might look in practice:
use Psr\Container\ContainerInterface;
class MyContainer implements ContainerInterface
{
private $services = [];
public function get(string $id)
{
if (!$this->has($id)) {
throw new NotFoundException("Service {$id} not found.");
}
return $this->services[$id];
}
public function has(string $id): bool
{
return isset($this->services[$id]);
}
public function set(string $id, $service): void
{
$this->services[$id] = $service;
}
}
// Usage
$container = new MyContainer();
$container->set('logger', new Logger());
if ($container->has('logger')) {
$logger = $container->get('logger');
$logger->log('PSR-11 is great!');
}Popular Containers Supporting PSR-11:
- Symfony DependencyInjection
- Laravel’s Container
- PHP-DI
- Pimple