Skip to content

Instantly share code, notes, and snippets.

@daveh
Last active September 7, 2024 05:37
Show Gist options
  • Save daveh/80901d23a6293a7cc4b363d6747b629b to your computer and use it in GitHub Desktop.
Save daveh/80901d23a6293a7cc4b363d6747b629b to your computer and use it in GitHub Desktop.
Dependency Injection in PHP (code to accompany https://youtu.be/TqMXzEK0nsA)
{
"autoload": {
"psr-4": {
"": "src/"
}
},
"require": {
"php-di/php-di": "^7.0"
}
}
<?php
class Container
{
private array $registry = [];
public function set(string $name, Closure $value): void
{
$this->registry[$name] = $value;
}
public function get(string $class_name): object
{
if (array_key_exists($class_name, $this->registry)) {
return $this->registry[$class_name]();
}
$reflector = new ReflectionClass($class_name);
$constructor = $reflector->getConstructor();
if ($constructor === null) {
return new $class_name;
}
$dependencies = [];
foreach ($constructor->getParameters() as $parameter) {
$type = $parameter->getType();
$dependencies[] = $this->get((string) $type);
}
return new $class_name(...$dependencies);
}
}
<?php
class Database
{
public function __construct(private string $host,
private string $name,
private string $user,
private string $password)
{
}
public function getConnection(): PDO
{
$dsn = "mysql:host={$this->host};dbname={$this->name}";
return new PDO($dsn, $this->user, $this->password);
}
}
<?php
require "vendor/autoload.php";
/*
$container = new Container;
$container->set(Database::class, function() {
return new Database(host: "",
name: "",
user: "",
password: "");
});
*/
$container = new DI\Container([
Database::class => function() {
return new Database(host: "",
name: "",
user: "",
password: "");
}
]);
$repository = $container->get(Repository::class);
$data = $repository->getAll();
var_dump($data);
<?php
class Repository
{
public function __construct(private Database $database)
{
}
public function getAll(): array
{
$pdo = $this->database->getConnection();
$stmt = $pdo->query("SELECT * FROM product");
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment