Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@iansltx
Last active May 16, 2023 22:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iansltx/0d4438252affb63e3d613d7ce233b386 to your computer and use it in GitHub Desktop.
Save iansltx/0d4438252affb63e3d613d7ce233b386 to your computer and use it in GitHub Desktop.
Dependency Injection Sample Code - 2023
<?php
class Container implements Psr\Container\ContainerInterface
{
protected $s = [];
function __set($k, $c) { $this->s[$k]=$c; }
function __get($k) { return $this->s[$k]($this); }
function get($k) { return $this->s[$k]($this); }
function has($k) { return isset($s[$k]); }
}
<?php
class Fizz { public function __toString() { return 'Fizz'; } }
class Buzz { public function __toString() { return 'Buzz'; } }
class FizzBuzz
{
public function __construct(private Fizz $fizz, private Buzz $buzz)
{
}
public function __invoke(int $i): string
{
if (!($i % 15)) return $this->fizz . $this->buzz;
if (!($i % 3)) return (string) $this->fizz;
if (!($i % 5)) return (string) $this->buzz;
return (string) $i;
}
}
<?php
// composer require php-di/php-di
use function DI\create;
class NeedsALogger
{
public function __construct(private Logger $logger)
{
}
}
class Logger {}
$c = new \DI\Container();
$c->set('LoggerInterface', create('Logger'));
// returns a NeedsALogger
var_dump($c->get('NeedsALogger'));
<?php
// composer require php-di/php-di
use function DI\autowire;
class NeedsALogger
{
public function __construct(private Logger $logger)
{
}
}
class Logger {}
$builder = new \DI\ContainerBuilder();
$builder->enableCompilation('/tmp');
$builder->addDefinitions([
'LoggerInterface' => autowire('Logger'),
'NeedsALogger' => autowire()
]);
$c = $builder->build();
var_dump($c->get('NeedsALogger'));
<?php
// composer require php-di/php-di
require 'FizzBuzz.php';
$c = new \DI\Container();
foreach (range(1, 15) as $i) {
echo $c->get('fizzBuzz')($i) . "\n";
}
<?php
// composer require psr/container
require 'Container.php';
require 'FizzBuzz.php';
$c = new Container;
$c->fizz = fn () => new Fizz;
$c->buzz = fn () => new Buzz;
$c->fizzBuzz = fn ($c) => new FizzBuzz($c->fizz, $c->buzz);
foreach (range(1, 15) as $i) {
echo $c->get('fizzBuzz')($i) . "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment