PHP design pattern registry of registration of multiple classes

  • 2020-05-12 02:21:05
  • OfStack

I've written a registry class before, but that one can't be registered for more than one class. The following is an array to store the class.
 
<?php 
// The base class  
class webSite {//1 A very simple base class  
private $siteName; 
private $siteUrl; 
function __construct($siteName,$siteUrl){ 
$this->siteName=$siteName; 
$this->siteUrl=$siteUrl; 
} 
function getName(){ 
return $this->siteName; 
} 
function getUrl(){ 
return $this->siteUrl; 
} 
} 
class registry {// The registry class   The singleton pattern  
private static $instance; 
private $values=array();// Use an array to store class names  
private function __construct(){}// This usage determines that the class cannot be instantiated directly  
static function instance(){ 
if (!isset(self::$instance)){self::$instance=new self();} 
return self::$instance; 
} 
function get($key){// Gets the class that has been registered  
if (isset($this->values[$key])){ 
return $this->values[$key]; 
} 
return null; 
} 
function set($key,$value){// Register class method  
$this->values[$key]=$value; 
} 
} 
$reg=registry::instance(); 
$reg->set("website",new webSite("WEB Development of notes ","www.chhua.com"));// Register the class  
$website=$reg->get("website");// For class  
echo $website->getName();// The output WEB Development of notes  
echo $website->getUrl();// The output www.chhua.com 
?> 

The purpose of the registry is to provide system-level object access. Some students will say that this is more than this 1, but it is really not necessary to register the class in small projects, if it is a big project, or very useful.

Related articles: