PHP code example of dvictorjhg / php-injector

1. Go to this page and download the library: Download dvictorjhg/php-injector 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/ */

    

dvictorjhg / php-injector example snippets




declare(strict_types=1);

inal class Logger
{
    public function log(string $message): string
    {
        return "[app] {$message}";
    }
}

final class ReportService
{
    public function __construct(private Logger $logger)
    {
    }

    public function generate(): string
    {
        return $this->logger->log('quarterly-report');
    }
}

$injector = new Injector([
    Logger::class,
]);

$service = Injector::inject(ReportService::class);

echo $service->generate();



declare(strict_types=1);

nterface Formatter
{
    public function format(string $value): string;
}

final class HtmlFormatter implements Formatter
{
    public function format(string $value): string
    {
        return "<report>{$value}</report>";
    }
}

final class Logger
{
}

final class RequestContext
{
    public function __construct(public string $source)
    {
    }
}

$injector = new Injector([
    Logger::class,
    Formatter::class => HtmlFormatter::class,
    RequestContext::class => new RequestContext('cli'),
    'env' => 'production',
]);

$firstLogger = Injector::inject(Logger::class);
$secondLogger = Injector::inject(Logger::class);
$formatter = Injector::inject(Formatter::class);
$context = Injector::inject(RequestContext::class);

var_dump($firstLogger === $secondLogger);
echo $formatter->format($context->source . ':' . Injector::inject('env'));



declare(strict_types=1);

inal class Logger
{
    public function __construct(public string $channel = 'app')
    {
    }
}
final class ReportController
{
    public function __construct(private Logger $logger)
    {
    }

    public function show(string $name): string
    {
        return "{$name} via {$this->logger->channel}";
    }
}

final class ReportJobs
{
    public static function warm(Logger $logger): string
    {
        return "warming {$logger->channel}";
    }
}

$injector = new Injector([
    Logger::class,
]);

echo Injector::inject([ReportController::class, 'show'], ['name' => 'sales']) . PHP_EOL;
echo Injector::inject(static fn (Logger $logger): string => "closure: {$logger->channel}") . PHP_EOL;
echo Injector::inject('ReportJobs::warm');



declare(strict_types=1);

inal class ReportLabel
{
    public static function build(string $name, bool $formal = false): string
    {
        return $formal ? "Report: {$name}" : $name;
    }
}

$injector = new Injector();

$args = [
    'name' => 'Quarterly Sales',
    'formal' => true,
];

echo Injector::inject([ReportLabel::class, 'build'], $args);



declare(strict_types=1);

nject;
use PHPInjector\DI\Injector;

final class Logger
{
    public function __construct(public string $channel = 'app')
    {
    }
}

final class ReportService
{
    public function __construct(
        private Logger $logger,
        #[Inject('env')] private string $environment,
    ) {
    }

    public function describe(): string
    {
        return "{$this->logger->channel}:{$this->environment}";
    }
}

$injector = new Injector([
    Logger::class,
    'env' => 'production',
]);

echo Injector::inject(ReportService::class)->describe();



declare(strict_types=1);

eton;
use PHPInjector\DI\Injector;

final class ConfigRepository implements Singleton
{
    private static ?self $instance = null;

    public string $name = 'main';

    private function __construct()
    {
    }

    public static function getInstance(): self
    {
        return self::$instance ??= new self();
    }
}

$injector = new Injector([
    ConfigRepository::class,
]);

$first = Injector::inject(ConfigRepository::class);
$second = Injector::inject(ConfigRepository::class);

var_dump($first === $second);
echo $first->name;



declare(strict_types=1);

se PHPInjector\DI\Attributes\Transient;

#[Transient]
final class ConnectionPool
{
    public readonly string $id;

    public function __construct()
    {
        $this->id = uniqid('conn-');
    }
}

$injector = new Injector();

$first = Injector::inject(ConnectionPool::class);
$second = Injector::inject(ConnectionPool::class);

var_dump($first === $second);
var_dump($first->id === $second->id);



declare(strict_types=1);

inal class Logger
{
    public function log(string $message): string
    {
        return "[app] {$message}";
    }
}

final class ReportService
{
    public function __construct(private Logger $logger)
    {
    }

    public function generate(): string
    {
        return $this->logger->log('child-report');
    }
}

$parent = new Injector([
    Logger::class,
]);
$child = new Injector();

$service = Injector::inject(ReportService::class);
echo $service->generate();



declare(strict_types=1);

inal class Logger
{
    public function __construct(public string $channel)
    {
    }
}

final class ReportBatch
{
    public static function channels(Logger ...$loggers): string
    {
        return implode(',', array_map(
            static fn (Logger $logger): string => $logger->channel,
            $loggers,
        ));
    }
}

$format = static fn (string $value): string => strtoupper($value);

$injector = new Injector([
    \Closure::class => $format,
    Logger::class => [
        new Logger('api'),
        new Logger('worker'),
    ],
]);

$formatted = Injector::inject(
    static fn (\Closure $format): string => $format('ready'),
);
$channels = Injector::inject([ReportBatch::class, 'channels']);

echo $formatted . PHP_EOL;
echo $channels;



declare(strict_types=1);

inal class Logger
{
    public function __construct(public string $channel)
    {
    }
}

$logger = new Logger('worker');
$target = static fn (Logger $logger): string => $logger->channel;

$byType = Injector::inject($target, [Logger::class => $logger]);
$byName = Injector::inject($target, ['logger' => $logger]);
$byPosition = Injector::inject($target, [$logger]);

echo $byType . PHP_EOL;
echo $byName . PHP_EOL;
echo $byPosition . PHP_EOL;



declare(strict_types=1);

e PHPInjector\Exceptions\InjectorException;

final class Logger
{
    public function __construct(public string $channel)
    {
    }
}

$logger = new Logger('worker');
$target = static fn (Logger $logger): string => $logger->channel;

try {
    Injector::inject($target, [
        Logger::class => $logger,
        0 => $logger,
    ]);
} catch (InjectorException $exception) {
    echo $exception->getMessage();
}



declare(strict_types=1);

args = ['string' => 'cache'];
$length = Injector::inject('strlen', $args);
echo $length;



declare(strict_types=1);

nject;
use PHPInjector\DI\Injector;
use PHPInjector\Exceptions\InjectorException;

final class Logger
{
    public function __construct(public string $channel = 'app')
    {
    }
}

final class ReportRunner
{
    public function run(
        Logger $logger,
        #[Inject('env')] string $environment,
        string $report = 'summary',
    ): string {
        return "{$logger->channel}:{$environment}:{$report}";
    }
}

$injector = new Injector([
    Logger::class,
    'env' => 'production',
]);

echo Injector::inject([ReportRunner::class, 'run'], [
    'report' => 'sales',
]) . PHP_EOL;
echo Injector::inject([ReportRunner::class, 'run']) . PHP_EOL;

$
bash
composer 
bash
composer install
php tools/check-docs.php
composer analyse
composer test