<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
vection-framework / dependency-injection example snippets
use Vection\Component\DependencyInjection\Traits\AnnotationInjection;
class MyApiController implements LoggerAwareInterface // Auto injection Logger via mapping in container config.
{
use AnnotationInjection;
#[Inject] private IdentityQueryService $identityQueryService;
public function __construct(CommandBusInterface $commandBus)
{
// Auto constructor parameter injection
}
}
public function __construct(FooBar $fooBar)
class Awesome
{
use AnnotationInjection;
#[Inject] protected FooBar $fooBar;
}
class Awesome
{
use AnnotationInjection;
#[Inject] protected FooBar $fooBar;
public function __construct()
{
// Cannot access $this->fooBar yet
}
// Alternative construction method, called immediately after the object is created with its dependencies
public function __init(): void
{
// Here you can access
$this->fooBar;
}
}
class Awesome
{
use AnnotationInjection;
public function __construct(FooBarInterface $fooBar)
{...}
}
class Awesome implements LoggerAwareInterface
{
public function setLogger(LoggerInterface $logger)
{...}
}
# First map the interface to the implementation
resolve(LoggerInterface::class)
->viaFactory(fn(Container $container) => new Logger())
,
# Now we can map the aware interface with the LoggerInterface by using the inject() method
resolve(LoggerAwareInterface::class)
->viaSetter('setLogger', LoggerInterface::class)
,
class Awesome
{
public function __inject(FooBar $fooBar)
{
$this->fooBar = $fooBar;
}
}
class AwesomeParent
{
use AnnotationInjection;
#[Inject] protected FooService $service;
public function __construct(FooBarInterface $fooBar)
{...}
}
class Awesome extends AwesomeParent
{
public function getFooBar()
{
return $this->fooBar;
}
}
$container = new Container();
// Create now your class where to start dependency injection
$myApplication = $container->get(MyApplication::class);
use function Vection\Component\DependencyInjection\resolve;
return [
// configuration here
];
$container = new Container();
$container->load('path/to/config/container.php');
$container->load('path/other/*/config/container.php');
// Not recommended writing type
$instruction = resolve(My\Awesome\MegaClass::class);
$instruction->viaFactory(....);
use function Vection\Component\DependencyInjection\resolve;
return [
resolve(My\Awesome\MegaClass::class)
->viaFactory(fn(Container $container) => new My\Awesome\MegaClass('example'))
,
];
$thirdPartyObject = new ThirdPartyObject(5, 'primitive');
$container->add($thirdPartyClass);
$cacheProvider = new Vection\Component\Cache\Provider\RedisCacheProvider(...);
$cache = new Vection\Component\Cache\Cache($cacheProvider);
$container = new Container();
$container->setCache($cache);
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.