Skip to content

Instantly share code, notes, and snippets.

@scilganon
Created January 31, 2018 20:31
Show Gist options
  • Save scilganon/bfa7c4c404ffff0cf9ca7160730a3a5c to your computer and use it in GitHub Desktop.
Save scilganon/bfa7c4c404ffff0cf9ca7160730a3a5c to your computer and use it in GitHub Desktop.
explanation of service container
<?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