Created
December 9, 2014 01:17
-
-
Save thepsion5/15ae50fd722f79eacbbf to your computer and use it in GitHub Desktop.
Simple Service Container Example
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 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