tereta / di
Lightweight Dependency Injection container for the Tereta Framework: typed-constructor auto-wiring, alias registration, factory generation and PSR-4 class discovery.
Requires
- php: >=8.4
- composer-runtime-api: ^2.0
- tereta/core: ^1.0
Suggests
- tereta/cache: Required by Tereta\Di\Services\Composer to persist PSR-4 class-discovery results across requests. Without it, scans run on every call to Composer::get().
README
π Π ΡΡΡΠΊΠΈΠΉ | English
Overview
Dependency Injection module. Automatically resolves class dependencies through typed constructor parameters.
Installation
composer require tereta/di
Dependency Injection (DI)
Automatic Dependency Resolution
Simply specify types in the constructor β the container will find and create the required instances:
class MyController
{
public function __construct(
protected RequestModel $requestModel,
protected Output $output
) {
}
}
Singleton
Classes using the Singleton trait are available via the ::singleton() static method. The container automatically resolves their dependencies on first call.
Connection::singleton();
Factory
Factories create instances through the container with DI support:
Model::factory()->create(['table' => 'customer']);
Class Registration
use Tereta\Di\Services\Container;
Container::singleton()->register(MyInterface::class, MyImplementation::class);
Class Scanning by Meta Attributes
The Composer service scans PSR-4 paths and finds all classes implementing a given interface or extending a base class. Used by the framework for automatic registration of controllers, commands, and models.
For example:
foreach (ComposerService::singleton()->get(CoreModel::class) as $model) {
$tableName = $model->getAttribute(CoreModel::class)?->getArgument('table');
$modelFactory->register($tableName, $model->getName());
}
Allowed Namespace Prefixes
To keep vendor scans bounded, Composer only walks PSR-4 prefixes from a whitelist. By default it covers Tereta\\ and Customisation\\. Downstream applications register additional prefixes via allowPrefix():
use Tereta\Di\Services\Composer;
Composer::singleton()
->allowPrefix('Acme\\')
->allowPrefix('MyApp\\Modules\\');
The trailing \\ is normalised, so both 'Acme' and 'Acme\\' are accepted. Use getAllowedPrefixes() to inspect the current whitelist.
Author and License
Author: Tereta Alexander
Website: tereta.dev
License: Apache License 2.0. See LICENSE.
www.ββββββββββββββββββββββββ βββββββββββββββββ ββββββ
ββββββββββββββββββββββββββββββββββββββββββββββββββ
βββ ββββββ ββββββββββββββ βββ ββββββββ
βββ ββββββ ββββββββββββββ βββ ββββββββ
βββ βββββββββββ βββββββββββ βββ βββ βββ
βββ βββββββββββ βββββββββββ βββ βββ βββ
.dev
Copyright (c) 2024-2026 Tereta Alexander