Last active
August 29, 2015 14:02
-
-
Save olekhy/2e6d92123be0fdbdfbe8 to your computer and use it in GitHub Desktop.
services loader w/o instanciate via NEW keyword
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 | |
abstract class AbstractService | |
{ | |
protected $options; | |
final protected function __construct($options) | |
{ | |
$this->options = $options; | |
} | |
} | |
class RealService extends AbstractService | |
{ | |
public function test() | |
{ | |
return $this->options; | |
} | |
} | |
class BadService | |
{ | |
} | |
class Loader extends AbstractService | |
{ | |
protected static $services; | |
public static function load($name, $options = null) | |
{ | |
if (!isset(static::$services[$name])) | |
{ | |
$service = new $name($options); | |
static::$services[$name] = $service; | |
} | |
return static::$services[$name]; | |
} | |
} | |
$options = [1,2,3]; | |
$service = Loader::load('RealService', $options); | |
var_dump($service->test()); | |
/* output | |
array(3) { | |
[0] => | |
int(1) | |
[1] => | |
int(2) | |
[2] => | |
int(3) | |
} | |
*/ | |
# - ! - | |
$options = ['o_O']; | |
$service = Loader::load('RealService', $options); | |
var_dump($service->test()); | |
/* output | |
array(3) { | |
[0] => | |
int(1) | |
[1] => | |
int(2) | |
[2] => | |
int(3) | |
} | |
*/ | |
# - ! - | |
//$service1 = new RealService(['a','b','c']); // PHP Fatal error: | |
~ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment