Skip to content

Instantly share code, notes, and snippets.

@SuoXC
Last active Aug 1, 2017
Embed
What would you like to do?
simple service locator + Facade(like in Laravel) implementation
<?php
class Facade{
private static $service = null;
public static function getKey(){
return 'world';
}
public static function __callstatic($method,$args){
if(!isset(self::$service)){
self::$service = ServiceLocator::getInstance()->getService(self::getKey());
}
call_user_func([self::$service,$method],$args);
}
}
class Hello{
public function say(){
echo 'hello';
}
}
class World{
public function say(){
echo 'world ffff';
}
}
class ServiceLocator{
private static $instance = null;
private $container = null;
public static function getInstance(){
if(!isset(self::$instance)){
self::$instance = new self;
}
return self::$instance;
}
private function __construct(){
$this->container = [
'hello' => new Hello,
'world' => new World,
];
}
public function getService($key){
if(!isset($this->container[$key])){
throw new Exception("service $key not exist");
}
return $this->container[$key];
}
}
Facade::say();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment