Skip to content

Instantly share code, notes, and snippets.

@thepsion5
Created December 9, 2014 01:17
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 thepsion5/15ae50fd722f79eacbbf to your computer and use it in GitHub Desktop.
Save thepsion5/15ae50fd722f79eacbbf to your computer and use it in GitHub Desktop.
Simple Service Container Example
<?php
class ServiceContainer
{
protected $services = [];
protected function setCallable($serviceKey, Callable $service)
{
$this->services[$serviceKey] = $service;
return $this;
}
protected function setInstance($serviceKey, $instance)
{
$this->services[$serviceKey] = function() use($instance)
{
return $instance;
});
return $this;
}
public function set($serviceKey, $service)
{
if($service instanceof Callable) {
return $this->setCallable($serviceKey, $service)
} elseif(is_object($service) {
return $this->setInstance($serviceKey, $service);
}
throw InvalidArgumentException('Services must be either an object instance or Callable, found [' . gettype($service) . '] instead.' );
}
public function get($serviceKey)
{
if( empty($this->services[$serviceKey]) ) {
throw new InvalidArgumentException("Cannot locate a service with the key [$serviceKey]");
}
return $this->services[$serviceKey]($this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment