-
-
Save appkr/ba98e6e31fe4b52ab7edc48bb4c7c24f to your computer and use it in GitHub Desktop.
simple service locator + Facade(like in Laravel) implementation
This file contains 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 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