Last active
February 7, 2020 18:42
-
-
Save orakaro/5997723 to your computer and use it in GitHub Desktop.
Sample of Inversion Of Control (IoC) and Singleton in PHP
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 IoC { | |
protected static $registry = array(); | |
protected static $shared = array(); | |
// Register | |
public static function register($name, Closure $resolve) | |
{ | |
static::$registry[$name] = $resolve; | |
} | |
// Singleton | |
public static function singleton($name, Closure $resolve) | |
{ | |
static::$shared[$name] = $resolve(); | |
} | |
// Resolve, consider register or singleton here | |
public static function resolve($name) | |
{ | |
if ( static::registered($name) ) | |
{ | |
$name = static::$registry[$name]; | |
return $name(); | |
} | |
if ( static::singletoned($name) ) | |
{ | |
$instance = static::$shared[$name]; | |
return $instance; | |
} | |
throw new Exception('Nothing registered with that name, fool.'); | |
} | |
// Check resigtered or not | |
public static function registered($name) | |
{ | |
return array_key_exists($name, static::$registry); | |
} | |
// Check singleton object or not | |
public static function singletoned($name) | |
{ | |
return array_key_exists($name, static::$shared); | |
} | |
} | |
class Book { | |
public $author; | |
public function setAuthor($author) | |
{ | |
$this->author = $author; | |
} | |
public function getAuthor() | |
{ | |
return $this->author; | |
} | |
} | |
// Register sample. Here $book1 and $book2 will end up with seperated instances of class Book | |
IoC::register('book',function(){ | |
$book = new Book; | |
$book->setAuthor('DTVD'); | |
return $book; | |
}); | |
$book1 = IoC::resolve('book'); | |
$book2 = IoC::resolve('book'); | |
echo "Register sample\n"; | |
var_dump($book1===$book2); | |
// Singleton sample. Here $bookSingleton1 and $bookSingleton2 will end up with same instances of class Book | |
IoC::singleton('bookSingleton',function(){ | |
$book = new Book; | |
$book->setAuthor('DTVD'); | |
return $book; | |
}); | |
$bookSingleton1 = IoC::resolve('bookSingleton'); | |
$bookSingleton2 = IoC::resolve('bookSingleton'); | |
echo "Singleton sample\n"; | |
var_dump($bookSingleton1===$bookSingleton2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment