1.1 工厂模式
, factory method or class generation object, not in code directly new
class Factory{
static function getDatabase(){
return new Mysql($host, $user, $pass);
}
}
#使用
Factory::getDatabase();
1.2 单例模式
to make an object of a class run only to create a
1. There is a private static object variable, which specializes in the object 2 of this class. There is a static method to create object 3. There is a private constructor to prevent external new Object 4. There is a clone method to prevent the clone return False
Reference article single case mode
Class Database {//single object attribute private static $instance;
Defining some global variables requires storing attributes private $props = Array ();
Private construction Method Private function __construct () {echo ' into construct! This class does not allow external creation of objects '; //Returns a single instance of the public static function getinstance () {///To determine if an instantiated object already exists if Empty (self:: $insta
NCE)) {//Can be override (dynamically parsed) Self:: $instance = new static ();
Can not be override (static resolution)//self:: $instance = new self ();
Return self:: $instance;
Public Function __clone () {return ' This class prohibits clone ';
}//Set property public function SetProperty ($key, $value) {$this->props[$key] = $value;
}//Get property Public Function Getpeoperty ($key) {return $this->props[$key];
}///Using $DBOBJ = Database::getinstance ();
$DBOBJ->setproperty (' Root_path ', '/www '); $DBOBJ->setproperty (' Tmp_path ', '/tmp ');
Next, delete the single Instance object and if you can get the property just added, the same object unset ($DBOBJ) is used;
$DBOBJ = Database::getinstance ();
echo $dbObj->getpeoperty (' Root_path '); echo $dbObj->getpeoperty (' Tmp_path ');
1.3 Registration mode, global sharing and exchange of objects
1. Add aliases to the same one that requires multiple use of object registration unified call to use, (for example, customers buy a machine must go to the factory to identify the organization to buy, not everyone to go to the factory to buy) 2. The next time you want to use an object, you don't need to use a factory or a single case pattern. Just get it on the register.
class Register (){
protected static $objects;
function set($alias, $object){
self::$objects[$alias] = $objects;
}
function get($alias){
return self::$objects[$alias];
}
function _unset($alias){
unset(self::$objects[$alias]);
}
}
2. Summary use
class Factory{
static function getDatabase(){
//单例模式获取数据对象
$dbObj = Database::getInstance();
//注册到全局树上
Register::set('db1', $dbObj);
}
}
#使用
//第一次主文件里面
Factory::getDatabase();
//以后使用数据库对象直接访问
Register::get('db1');