1. 程式人生 > >設計模式之註冊器模式(PHP實現)

設計模式之註冊器模式(PHP實現)

註冊的時候感覺工廠模式還是要的,防止業務邏輯裡面的類名改名或者加引數。工廠靜態方法呼叫後Register下。

index.php

<?php
define('BASEDIR',__DIR__);
include BASEDIR.'/Core/Loader.php';
spl_autoload_register('\\Core\\Loader::autoload');

//一般初始化環境時候註冊類 然後每次從註冊樹上面拿類。
\Core\Factory::createDatabases();

$db= \Core\Register::get('db1');
$db->conn();
?>

database.php
<?php
namespace Core;
class Database{
    protected static $db;
    private function __construct(){

    }
    public static function getInstance(){
        if(self::$db){
            return self::$db;
        }else{
            self::$db=new self();
            return self::$db;
        }
    }
    public function conn(){
        echo "this is a method of connect database;";
    }
}
?>

register.php
<?php
namespace Core;
class  Register{
    protected static $objects;
    static function set($alias,$object){
        self::$objects[$alias]=$object;
    }
    static function get($name){
        return self::$objects[$name];
    }
    function _unset($alias){
        unset(self::$objects[$alias]);
    }
}

Factory.php
<?php
namespace Core;
class Factory{
    public static function createDatabases(){
        $db=Database::getInstance();
        Register::set('db1',$db);
       // return $db;
    }
}