dikki/ci4-di

Implement and Use Dependency Injection in CodeIgniter 4.

Installs: 4

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/dikki/ci4-di

0.0.2 2026-01-10 19:08 UTC

This package is auto-updated.

Last update: 2026-01-10 19:09:26 UTC


README

Robust Dependency Injection for CodeIgniter 4, powered by League Container.

Features

  • PSR-11 Compliant Container.
  • Autowiring: Automatically resolve dependencies for classes without manual configuration.
  • Service Providers: Organize service registrations.
  • Aliases: Bind services to aliases.
  • Shared Services: Support for Singleton pattern.
  • Seamless Integration: Replaces CI4's Controller constructor injection mechanism.

Installation

composer require dikki/ci4-di

Initialize the configuration:

php spark container:publish

This will create app/Config/Container.php where you can configure services.

Setup

Modify app/Config/Services.php to define the codeigniter service override. This ensures the application uses the DI Container for Controller instantiation.

<?php

namespace Config;

use CodeIgniter\Config\BaseService;
use CodeIgniter\Config\App;
use Dikki\Container\Application;

class Services extends BaseService
{
    // ...

    public static function codeigniter(?App $config = null, bool $getShared = true)
    {
        if ($getShared) {
            return static::getSharedInstance('codeigniter', $config);
        }

        $config = $config ?? config('App');

        return new Application($config);
    }
}

Usage

Autowiring

Most of the time, you don't need to do anything. If your Controller injects a service, it will be automatically resolved.

class Home extends BaseController
{
    public function __construct(
        private UserService $userService
    ) {}
}

Manual Configuration

You can explicitly define services in app/Config/Container.php:

// app/Config/Container.php
public array $services = [
    // Interface binding
    'App\Interfaces\UserRepoInterface' => 'App\Repositories\UserRepo',
    
    // Concrete value or class
    'mailer' => 'App\Services\Mailer',
];

public array $shared = [
    // Singleton services
    'db.connection' => 'App\Database\Connection',
];

Service Providers

For complex setup, use Service Providers.

// app/Config/Container.php
public array $providers = [
    'App\Providers\AppServiceProvider',
];

Accessing the Container

You can access the container instance globally:

use Dikki\Container\Container;

$container = Container::getInstance();
$service = $container->get('my_service');