Created
October 9, 2011 00:42
-
-
Save thiagophx/1273118 to your computer and use it in GitHub Desktop.
ServiceLocator 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 | |
abstract class ServiceLocator | |
{ | |
protected static $locator; | |
public static function load(ServiceLocator $locator) | |
{ | |
self::$locator = $locator; | |
} | |
public static function locator() | |
{ | |
return self::$locator; | |
} | |
} | |
interface DAOServiceLocator | |
{ | |
public function db(); | |
} | |
class Db | |
{ | |
public function connect() | |
{ | |
return 'connected'; | |
} | |
} | |
class DAOLocator extends ServiceLocator implements DAOServiceLocator | |
{ | |
public function db() | |
{ | |
return new Db(); | |
} | |
} | |
class DAO | |
{ | |
public function listAll() | |
{ | |
echo ServiceLocator::locator()->db()->connect(); | |
} | |
} | |
ServiceLocator::load(new DAOLocator()); | |
$dao = new DAO(); | |
$dao->listAll(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment