Created
January 31, 2018 20:31
-
-
Save scilganon/bfa7c4c404ffff0cf9ca7160730a3a5c to your computer and use it in GitHub Desktop.
explanation of service container
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Battery { | |
/** | |
* Battery constructor. | |
* @param int $procent | |
*/ | |
public function __construct(int $procent) | |
{ | |
$this->procent = $procent; | |
} | |
} | |
class Calc { | |
/** | |
* Calc constructor. | |
*/ | |
public function __construct(Battery $battery) | |
{ | |
$this->battery = $battery; | |
} | |
} | |
class Lamp { | |
/** | |
* Lamp constructor. | |
*/ | |
public function __construct(Battery $battery) | |
{ | |
$this->battery = $battery; | |
} | |
} | |
class Container { | |
protected $services = [ | |
// Battery::class => function(){} | |
]; | |
public function get(string $alias){ | |
return $this->services[$alias](); | |
} | |
public function set(string $alias, callable $factory){ | |
$this->services[$alias] = $factory; | |
} | |
} | |
$container = new Container(); | |
$container->set(Battery::class, function(){ | |
return new Battery(12); | |
}); | |
$container->set(Calc::class, function() use ($container){ | |
$battery = $container->get(Battery::class); | |
return new Calc($battery); | |
}); | |
$container->set(Lamp::class, function() use ($container){ | |
$battery = $container->get(Battery::class); | |
return new Lamp($battery); | |
}); | |
$calc = $container->get(Calc::class); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment