1. Go to this page and download the library: Download lighthouse/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/ */
lighthouse / container example snippets
use Lighthouse\Container\Container;
class Logger
{
public function log(string $message): void
{
echo $message;
}
}
class UserService
{
public function __construct(
private Logger $logger
) {}
}
$container = new Container();
// Automatically resolves Logger dependency
$userService = $container->get(UserService::class);
interface CacheInterface
{
public function get(string $key): mixed;
}
class RedisCache implements CacheInterface
{
public function get(string $key): mixed
{
// Redis implementation
}
}
$container->bind(CacheInterface::class, RedisCache::class);
$cache = $container->get(CacheInterface::class);
// Returns instance of RedisCache
$container->bind(Database::class, function (Container $c) {
$config = $c->get(Config::class);
return new Database(
host: $config->get('db.host'),
user: $config->get('db.user'),
pass: $config->get('db.pass')
);
});
$logger = new Logger();
$container->instance(Logger::class, $logger);
// Always returns the same $logger instance
$container->factory(RequestId::class, function () {
return new RequestId(uniqid());
});
$id1 = $container->get(RequestId::class); // RequestId with unique id
$id2 = $container->get(RequestId::class); // Different RequestId
class OrderController
{
public function store(OrderService $service, Validator $validator): Order
{
// ...
}
}
$controller = new OrderController();
// Automatically resolves OrderService and Validator
$result = $container->call($controller, 'store');
// With additional parameters
$result = $container->call($controller, 'update', ['id' => 123]);
// Check if entry exists
$container->has(Logger::class); // true/false
// Get entry (throws NotFoundException if not found)
$container->get(Logger::class);
use Lighthouse\Container\Exception\NotFoundException;
use Lighthouse\Container\Exception\ContainerException;
try {
$container->get('UnknownClass');
} catch (NotFoundException $e) {
// Entry not found
} catch (ContainerException $e) {
// Error during resolution (circular dependency, etc.)
}
class A {
public function __construct(B $b) {}
}
class B {
public function __construct(A $a) {}
}
$container->get(A::class);
// Throws: ContainerException: Circular dependency detected while resolving "A"
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.