Skip to content

Instantly share code, notes, and snippets.

@olekhy
Last active August 29, 2015 14:02
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 olekhy/2e6d92123be0fdbdfbe8 to your computer and use it in GitHub Desktop.
Save olekhy/2e6d92123be0fdbdfbe8 to your computer and use it in GitHub Desktop.
services loader w/o instanciate via NEW keyword
<?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