Skip to content

Instantly share code, notes, and snippets.

@jocoonopa
Last active April 5, 2019 14:58
Show Gist options
  • Save jocoonopa/5051fe4ed890c079f80e11c66dadcfaa to your computer and use it in GitHub Desktop.
Save jocoonopa/5051fe4ed890c079f80e11c66dadcfaa to your computer and use it in GitHub Desktop.
Ioc-Simple-Example
<?php
class ComicBook implements Readable
{
public function read(NeedOne $n1, NeedTwo $n2, NeedThree $n3)
{
return $n3->seeWord(
$n2->seeRaw(
$n1->seePage($this)
)
);
}
}
<?php
class Eye
{
public function seePage()
{
return 1;
}
public function seeRaw($page)
{
$raws = [
'Hello world',
'Say good night',
];
return data_get($raws, ($page - 1), '');
}
public function seeWord($raw)
{
return explode(' ', $raw);
}
}
<?php
interface NeedOne {}
interface NeedTwo {}
interface NeedThree {}
$eye = new Eye;
MyContainer::bind(NeedOne::class, $eye);
MyContainer::bind(NeedTwo::class, $eye);
MyContainer::bind(NeedThree::class, $eye);
$people = new People();
$people->read(new ComicBook()); // output: ['Hello', 'world']
<?php
class MyContainer
{
protected static $container;
public static function bind($name, Callable $resolver)
{
static::$container[$name] = $resolver;
}
public static function make($name)
{
if (! isset(static::$container[$name])) {
throw new Exception("Binding does not exist in containeer");
}
$resolver = static::$container[$name];
return $resolver();
}
}
<?php
class People
{
public function read(Readable $readable)
{
$params = [];
$receipeParameters = (new ReflectMethod($readable, 'read'))->getParameters();
foreach ($receipeParameters as $parameter) {
$params[] = MyContainer::make($parameter->getType());
}
return call_user_func_array(
[
$readable, 'read',
],
$params
);
}
}
<?php
interface Readable{}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment