1. Go to this page and download the library: Download luizfilipezs/container 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/ */
luizfilipezs / container example snippets
$container = new Container();
$container->set(MyInterface::class, MyClass::class);
$myObject = $container->get(MyInterface::class);
use Luizfilipezs\Container\Attributes\Lazy;
#[Lazy]
class UserService
{
public function __contruct(private readonly UserRepositoryInterface $userRepository)
{
echo 'Constructor was called.';
}
public function getAll(): array
{
return $this->userRepository->findAll();
}
}
$userService = $container->get(UserService::class);
$users = $userService->getAll(); // 'Constructor was called.'
use Luizfilipezs\Container\Attributes\{Lazy, LazyInitializationSkipped};
#[Lazy]
class MyClass
{
#[LazyInitializationSkipped]
public string $skippedProp = 'foo';
public string $normalProp = 'bar';
public function __construct()
{
echo 'Constructor was called.';
}
}
$myInstance = $container->get(MyClass::class);
$myInstance->skippedProp;
$myInstance->normalProp; // 'Constructor was called.'
use Luizfilipezs\Container\Enums\ContainerEvent;
$container->eventHandler->on(
event: ContainerEvent::LAZY_CLASS_CONSTRUCTED,
callback: static function (string $className, object $instance) {
echo "{$className}::__construct was called.";
},
);
$instance = $container->get(MyClass::class);
$instance->foo; // 'MyClass::__construct was called.'
use Luizfilipezs\Container\Attributes\Inject;
enum ApiConstant: string
{
case API_KEY = 'API_KEY';
case API_SECRET = 'API_SECRET';
}
$container->setValue(ApiConstant::API_KEY, 'my_api_key');
$container->setValue(ApiConstant::API_SECRET, 'my_api_secret');
class ApiService
{
public function __construct(
#[Inject(ApiConstant::API_KEY)] string $apiKey,
#[Inject(ApiConstant::API_SECRET)] string $apiSecret,
) {}
}
// call __construct with: 'my_api_key', 'my_api_secret'
$apiService = $container->get(ApiService::class);
$container->setValue('SOME_INT', 123);
class MyClass
{
public function __contruct(#[Inject('SOME_INT')] float $value) {}
}
$object = $container->get(MyClass::class);
// ContainerException: Container cannot inject "SOME_INT". It is not the same
// type as the parameter. Expected float, got int.
$container = new Container(strict: true);
// ContainerException, because there is no explicit definition for "SomeClass"
$instance = $container->get(SomeClass::class);