Rumah >pembangunan bahagian belakang >tutorial php >PHP 设计模式系列 -- 注册模式(Registry)
注册模式 (Registry)也叫做注册树模式,注册器模式。注册模式为应用中经常使用的对象创建一个中央存储器来存放这些对象 —— 通常通过一个只包含静态方法的抽象类来实现(或者通过单例模式)。
Registry.php
<?phpnamespace DesignPatterns\Structural\Registry;/** * class Registry */abstract class Registry{ const LOGGER = 'logger'; /** * @var array */ protected static $storedValues = array(); /** * sets a value * * @param string $key * @param mixed $value * * @static * @return void */ public static function set($key, $value) { self::$storedValues[$key] = $value; } /** * gets a value from the registry * * @param string $key * * @static * @return mixed */ public static function get($key) { return self::$storedValues[$key]; } // typically there would be methods to check if a key has already been registered and so on ...}
Tests/RegistryTest.php
<?phpnamespace DesignPatterns\Structural\Registry\Tests;use DesignPatterns\Structural\Registry\Registry;class RegistryTest extends \PHPUnit_Framework_TestCase{ public function testSetAndGetLogger() { Registry::set(Registry::LOGGER, new \StdClass()); $logger = Registry::get(Registry::LOGGER); $this->assertInstanceOf('StdClass', $logger); }}