meow/di

Dependency injection container

v0.1.0 2021-11-12 21:46 UTC

This package is auto-updated.

Last update: 2024-11-13 05:06:02 UTC


README

Dependency injection container for PHP

namespace: meow\di

Installation

To install this plugin use following command

composer require meow/di

Usage

Example how to use this container

Creating new container

To create new container you can use code as follows

$container = new ApplicationContainer();

Registering services

Services are defined as array [interface => class] and have to be defined before you can resolve your classes.

protected array $services = [
    BaseServiceInterface::class => BaseService::class
];

// add services to container
foreach ($this->services as $k => $v) {
    $container->set($k, $v);
}

Resolving classes

With DI container you don't need to create new instances in constructor (as in example controller - check tests).

class MainController
{
    protected User $user;

    protected BaseServiceInterface $service;

    public function __construct(BaseServiceInterface $service, User $user)
    {
        $this->user = $user;
        $this->service = $service;
    }
}

now you can resolve controller with container

/** @var MainController $controller */
$controller = $container->resolve(MainController::class);

License: MIT