Dependency injection
Constructors receive dependencies. The application's DI class assembles them through typed PHP factories.
Composer's autoloader loads class definitions when they are used. The factories in DI construct objects and supply their dependencies. This keeps class loading and object assembly separate, whether a class belongs to your application or an installed library.
On this page
The naming convention
Use a class named DI in src/DI.php, in the namespace your project maps to src/. For example, mapping App\\ to src/ makes the class App\DI. Use static factories named getRatingSummary(), getArticleRepository(), and so on. Controllers and CLI programs call the public factories to obtain the collaborators they need. The injected objects receive their dependencies through constructors rather than calling DI themselves.
get does not imply sharing: the factory explicitly chooses whether to create or reuse an object. These are ordinary PHP methods, with no required container or separate wiring configuration.
One class per file
This standalone example formats a rating. It uses App as an example namespace; choose your own prefix and keep the Composer mapping, declarations and imports consistent. Use PHP 8.3–8.6 and Composer, and create the following files in a new project directory:
composer.json
src/
DI.php
DisplaySettings.php
RatingLabels.php
RatingSummary.php
bin/
rating.php
File: composer.json
{
"name": "example/ratings",
"type": "project",
"require": {
"php": "^8.3"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
File: src/DisplaySettings.php
<?php
declare(strict_types=1);
namespace App;
final class DisplaySettings
{
public function __construct(public readonly int $maximum) {}
}
File: src/RatingLabels.php
<?php
declare(strict_types=1);
namespace App;
final class RatingLabels
{
public function __construct(private DisplaySettings $settings) {}
public function scale(): string
{
return "out of " . $this->settings->maximum;
}
}
File: src/RatingSummary.php
<?php
declare(strict_types=1);
namespace App;
final class RatingSummary
{
public function __construct(private RatingLabels $labels) {}
public function describe(float $score): string
{
return $score . " " . $this->labels->scale();
}
}
File: src/DI.php
<?php
declare(strict_types=1);
namespace App;
final class DI
{
public static function getRatingSummary(): RatingSummary
{
return new RatingSummary(self::getRatingLabels());
}
public static function getDisplaySettings(): DisplaySettings
{
static $settings = null;
return $settings ??= new DisplaySettings(maximum: 5);
}
private static function getRatingLabels(): RatingLabels
{
return new RatingLabels(self::getDisplaySettings());
}
}
Call DI from a command
File: bin/rating.php
<?php
declare(strict_types=1);
use App\DI;
require __DIR__ . "/../vendor/autoload.php";
echo DI::getRatingSummary()->describe(4.5), "\n";
Run from the project directory:
composer install
php bin/rating.php
Output: 4.5 out of 5.
The call reveals the graph: summary → labels → settings. The command loads the autoloader and obtains the summary. The summary and labels receive their dependencies through constructors.
Call DI from a controller
For an HTTP version, create the following endpoint. It requires the configured environment to load Composer through a bootstrap before the controller runs.
File: web/GET/rating.php
<?php
declare(strict_types=1);
use App\DI;
echo DI::getRatingSummary()->describe(4.5);
Add the matching route to the project's existing protected routing file. For Apache, insert it before the final file check and dispatch block.
rewrite ^/rating$ /$handler_method/rating.php last;
RewriteRule ^/rating$ /%{ENV:handler_method}/rating.php
The controller obtains its collaborator exactly as the command does. The model and views remain independent of DI and HTTP. In the small application, the read controllers call DI::getArticleRepository() and construct their views directly.
Choose visibility and sharing
Public factories are entry points for callers. Private factories are construction details. Here the summary and settings are public; the labels are internal to DI.
Returning new creates a fresh object on each call. A local static retains an object for later calls in the same PHP execution. The example creates fresh summaries and labels but shares the settings, which are constructed only when needed.
A static method does not itself share its result. Sharing is the explicit choice inside the method. Under PHP-FPM, these objects do not survive the request; in a long-running PHP process they can survive multiple calls or tasks.
Keep decisions explicit
An interface implementation, a connection or a configuration value is an application choice. Write that choice in its factory. Constructor types make relationships visible, but they cannot choose credentials or infer every object's lifetime.
Objects that merely carry data and views constructed from that data do not automatically need DI factories. Use new directly when it is clearer.
An optional development tool can help write factories. The resulting code remains ordinary, application-owned PHP.