PHP code example of suhock / dependency-injection

1. Go to this page and download the library: Download suhock/dependency-injection library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

suhock / dependency-injection example snippets


use Suhock\DependencyInjection\ContainerBuilder;

$container = ContainerBuilder::createDefault()
    ->addSingleton(MyApplication::class)
    ->addSingleton(Logger::class, fn () => new FileLogger('myapp.log'))
    ->addTransient(HttpClient::class, CurlHttpClient::class)
    ->addTransient(CurlHttpClient::class)
    ->build();

$container->get(MyApplication::class)->run();

use Suhock\DependencyInjection\ContainerBuilder;

$builder = ContainerBuilder::createDefault();

$builder
    // Inject the constructor's dependencies
    ->addSingleton(MyApplication::class)

    // Manually construct an instance with factory
    ->addSingleton(MyLogger::class, fn () => new FileLogger('myapp.log'))

    // Provide a pre-constructed instance and promise to dispose it later ourselves
    ->addSingleton(RequestContext::class, $requestContext, shouldDispose: false)

    // Alias an interface to an implementing type
    ->addTransient(HttpClient::class, CurlHttpClient::class)

    // Take the autowired instance and configure it before handing it back
    ->addTransient(
        CurlHttpClient::class,
        function (CurlHttpClient $client, Logger $logger): CurlHttpClient {
            $client->addLogger($logger);

            return $client;
        }
    );

$container = $builder->build();

$container
    ->get(MyApplication::class)
    ->handleRequest();

class MyApplication
{
    // The constructor arguments will be provided by the container
    public function __construct(
        private readonly HttpClient $client,
        private readonly Logger $logger,
    ) {}
}

class MyRouter
{
    public function __construct(
        private readonly ContainerInterface $container,
    ) {}

    public function routeRequest(string $method, string $path): void
    {
        $controllerClassName = $this->getControllerClassName($path);
        $controller = $this->container->get($controllerClassName);
        $controller->handleRequest($method);
    }
}

$container = $builder->build();

use Suhock\DependencyInjection\Validation\ContainerValidationException;

try {
    $container = $builder->build();
} catch (ContainerValidationException $e) {
    foreach ($e->getIssues() as $issue) {
        // $issue->kind, $issue->className, $issue->key, $issue->message
        echo $issue->kind->name . ': ' . $issue->serviceId() . ' - ' . $issue->message . "\n";
    }
}

use Suhock\DependencyInjection\Cache\OpcacheCache;
use Suhock\DependencyInjection\ContainerBuilder;

$container = ContainerBuilder::createDefault(new OpcacheCache(__DIR__ . '/var/cache'))
    ->addSingleton(MyApplication::class)
    ->build();

$graph = $builder->exportDependencyGraph();

// The graph roots (services nothing injects) are the ids no edge targets.
// They are typically the entry points your application resolves itself.
$targets = array_map(fn ($edge) => $edge->targetId, $graph->edges);
$roots = array_diff($graph->serviceIds, $targets);

// Or render it:
foreach ($graph->edges as $edge) {
    echo "\"$edge->sourceId\" -> \"$edge->targetId\";\n"; // Graphviz
}

$builder->addSingleton(MyService::class);

$builder->addScoped(MyService::class);

$builder->addTransient(MyService::class);

use Suhock\DependencyInjection\ContainerBuilder;

$container = ContainerBuilder::createDefault()
    ->addSingleton(LoggerInterface::class, FileLogger::class)
    ->addSingleton(FileLogger::class)
    ->addScoped(RequestContext::class)
    ->addTransient(RequestHandler::class)
    ->build();

$scope = $container->createScope();

try {
    // Both handlers share one RequestContext; the logger is the container-wide
    // singleton.
    $scope->get(RequestHandler::class)->handle();
    $scope->get(RequestHandler::class)->handle();
} finally {
    $scope->dispose();
}

final class QueueWorker
{
    public function __construct(private readonly ScopeFactoryInterface $scopes)
    {
    }

    public function process(Message $message): void
    {
        $scope = $this->scopes->createScope();

        try {
            $scope->get(MessageHandler::class)->handle($message);
        } finally {
            $scope->dispose();
        }
    }
}


// public/worker.php

use Suhock\DependencyInjection\ContainerBuilder;

mpilation and validation cost is paid a single time, before the loop
// starts, not per request.
$container = ContainerBuilder::createDefault()
    ->addSingleton(FileLogger::class)
    ->addSingleton(Logger::class, FileLogger::class)
    // FrankenPHP refreshes the superglobals before each request.
    ->addScoped(RequestContext::class, fn () => RequestContext::fromGlobals())
    ->addTransient(RequestHandler::class)
    ->build();

$handler = static function () use ($container): void {
    $scope = $container->createScope();

    try {
        $scope->get(RequestHandler::class)->handle();
    } finally {
        $scope->dispose();
    }
};

while (frankenphp_handle_request($handler)) {
    gc_collect_cycles();
}

use Suhock\Disposable\DisposableInterface;

final class UnitOfWork implements DisposableInterface
{
    public function __construct(
        private readonly Connection $connection,
    ) {}

    public function dispose(): void
    {
        $this->connection->rollBackIfActive();
    }
}

use Suhock\DependencyInjection\ContainerBuilder;

$container = ContainerBuilder::createDefault()
    ->addScoped(Connection::class)
    ->addScoped(UnitOfWork::class)
    ->build();

$scope = $container->createScope();

try {
    $scope->get(UnitOfWork::class)->commit();
} finally {
    // Disposes UnitOfWork, then Connection.
    $scope->dispose();
}

$container = ContainerBuilder::createDefault()
    ->addSingleton(ConnectionPool::class) // implements DisposableInterface
    ->build();

// ... run the application ...

$container->dispose();

// The pool is closed elsewhere; the container must not dispose it.
$builder->addSingleton(ConnectionPool::class, $pool, shouldDispose: false);

// It applies to services the container creates too, not just supplied instances.
$builder->addScoped(Connection::class, shouldDispose: false);

class ContainerBuilder
{
    /**
     * @template TClass of object
     * @template TImplementation of TClass
     * @param class-string<TClass> $className
     * @param class-string<TImplementation>|TClass|callable|null $source
     * @return $this
     */
    public function addSingleton(
        string $className,
        string|callable|object|null $source = null,
        bool $shouldDispose = true,
    ): static;

    public function addScoped(
        string $className,
        string|callable|null $source = null,
        bool $shouldDispose = true,
    ): static;

    public function addTransient(
        string $className,
        string|callable|null $source = null,
        bool $shouldDispose = true,
    ): static;
}

$builder->addSingleton(MyService::class);

$builder
    ->addSingleton(HttpClient::class, CurlHttpClient::class)
    ->addSingleton(CurlHttpClient::class);

$builder->addSingleton(MyService::class, fn () => new MyService('foo'));
$builder->addScoped(RequestContext::class, RequestContext::fromGlobals(...));
$builder->addTransient(Report::class, [$reports, 'next']);

$builder->addSingleton(
    Mailer::class,
    fn (AppConfig $config) => new Mailer($config->mailerTransport),
);

$builder->addTransient(
    Logger::class,
    fn (FileWriter $writer) => new class($writer) implements Logger {
        public function __construct(
            private readonly FileWriter $writer,
        ) {}

        public function log(string $message): void
        {
            $this->writer->writeLine($message);
        }
    }
);

$builder->addTransient(
    CurlHttpClient::class,
    function (CurlHttpClient $client, Logger $logger): CurlHttpClient {
        $client->addLogger($logger);
        return $client;
    },
);

$builder->addTransient(
    CurlHttpClient::class,
    'api',
    function (#[Key('api')] CurlHttpClient $client, Logger $logger): CurlHttpClient {
        $client->addLogger($logger);
        return $client;
    },
);

final class RetryingConnection extends Connection
{
    public function __construct(private readonly Connection $inner) {}
}

$request = new Request($_SERVER, $_GET, $_POST, $_COOKIE);
$builder->addSingleton(Request::class, $request);

class ContainerBuilder
{
    /**
     * @template TClass of object
     * @template TImplementation of TClass
     * @param class-string<TClass> $className
     * @param class-string<TImplementation>|TClass|callable|null $source
     * @return $this
     */
    public function addKeyedSingleton(
        string $className,
        string|UnitEnum $key,
        string|callable|object|null $source = null,
        bool $shouldDispose = true,
    ): static;

    public function addKeyedScoped(
        string $className,
        string|UnitEnum $key,
        string|callable|null $source = null,
        bool $shouldDispose = true,
    ): static;

    public function addKeyedTransient(
        string $className,
        string|UnitEnum $key,
        string|callable|null $source = null,
        bool $shouldDispose = true,
    ): static;
}

class Container
{
    /**
     * @template TClass of object
     * @param class-string<TClass> $className
     * @return TClass
     */
    public function get(string $className, string|UnitEnum|null $key = null): object;

    public function has(string $className, string|UnitEnum|null $key = null): bool;
}

$container = $builder
    ->addSingleton(
        Settings::class,
        fn () => JsonSettings::fromFile('default.json'),
    )
    ->addKeyedSingleton(
        Settings::class,
        'admin',
        fn () => JsonSettings::fromFile('admin.json'),
    )
    ->build();

// Resolves the unkeyed Settings service.
$settings = $container->get(Settings::class);

// Resolves the Settings service under the 'admin' key.
$adminSettings = $container->get(Settings::class, 'admin');

use Suhock\DependencyInjection\Key;

class AdminController
{
    public function __construct(
        /*
         * Resolved from the unkeyed Settings service.
         */
        private readonly Settings $settings,

        /*
         * Resolved from the Settings service under the 'admin' key.
         */
        #[Key('admin')]
        private readonly Settings $adminSettings,
    ) {}
}

class Injector
{
    /**
     * @template TResult
     * @param callable(mixed...): TResult $function
     * @param array<int|string, mixed> $params
     * @return TResult
     */
    public function call(callable $function, array $params = []): mixed;

    /**
     * @template TClass of object
     * @param class-string<TClass> $className
     * @param array<int|string, mixed> $params
     * @return TClass
     */
    public function instantiate(string $className, array $params = []): object;
}

use Suhock\DependencyInjection\ContainerBuilder;
use Suhock\DependencyInjection\Injector;

// Configure and build the container
$container = ContainerBuilder::createDefault()
    ->addSingleton(Router::class)
    // ... add controllers and services ...
    ->build();

// Create an injector backed by the built container
$injector = Injector::createDefault($container);

// Fetch the application router from the container
$router = $container->get(Router::class);
$controller = $router->getControllerFromRequest($_SERVER);
$params = map_query_to_params($_GET);

// Call the controller's handleGet() method, injecting the indicated parameter
// values and resolving the rest of the parameter list from the container.
$page = $injector->call(
    $controller->handleGet(...),
    $params,
);

class MyApplication
{
    public function __construct(
        private readonly HttpClient $httpClient,
    ) {}
}

class MyApplication
{
    public function __construct(
        private readonly ?HttpClient $httpClient,
    ) {}
}

class MyApplication
{
    public function __construct(
        private readonly HttpClient $httpClient,
        private readonly string $homeUrl = '',
        private readonly int $timeout = 0,
        private readonly array $otherOptions = [],
    ) {}
}

class MyApplication
{
    public function __construct(
        private readonly HttpClient|GopherClient|string $client,
    ) {}
}

class MyApplication
{
    public function __construct(
        private readonly HttpClient&Serializable $httpClient,
    ) {}
}

use Suhock\DependencyInjection\Lazy;

class ReportController
{
    public function __construct(
        #[Lazy]
        private readonly PdfRenderer $renderer,
    ) {}
}

use Suhock\DependencyInjection\DependencyInjectionException;

try {
    $app = $container->get(MyApplication::class);
} catch (DependencyInjectionException $e) {
    // Handle any dependency injection failure.
}

ContainerBuilder::createDefault(?CacheInterface $cache = null): self

interface CacheInterface
{
    public function tryGet(string $id, mixed &$value): bool;

    public function set(string $id, mixed $value): void;
}

use Suhock\DependencyInjection\Cache\ApcuCache;
use Suhock\DependencyInjection\ContainerBuilder;

$builder = ContainerBuilder::createDefault(new ApcuCache());

use Suhock\DependencyInjection\Cache\OpcacheCache;
use Suhock\DependencyInjection\ContainerBuilder;

$builder = ContainerBuilder::createDefault(new OpcacheCache(__DIR__ . '/var/cache'));
shell
frankenphp php-server --worker public/worker.php