八. .PHP模式設計----企業模式(1)

來源:互聯網
上載者:User

標籤:blog   http   io   ar   os   使用   sp   for   檔案   


(*暫時未拆分前端控制器和應用控制器,全部整合在Command類實現)

1 註冊表模式//註冊表模式//註冊表模式用於提供一個系統層級對象,在任何地方都方便訪問(可以使用單例模式)class Registry{    private static $instance;    private $request;    private function __construct(){}    static function instance(){        if(!isset(self::$instance)){            self::$instance=new self();        }        return self::$instance;    }    function getRequest(){        $this->request;    }    function setRequest(Request $request){        $this->request=$request;    }}class Request{}  2 三種範圍下的註冊表namespace woo\controller;class Request{}class Complex{}//建立一個具有範圍的註冊表模式//請求層級註冊表namespace woo\base;use woo;abstract class Registry{    abstract protected function get($key);    abstract protected function set($key,$val); }class RequestRegistry extends Registry{    private $values=array();    private static $instance;    private function __construct(){}    //返回唯一執行個體    static function instance(){        if(!isset(self::$instance)){            self::$instance=new self();        }        return self::$instance;    }    protected function get($key){        if(isset($this->values[$key])){            return isset($this->values[$key]);        }        return null;    }    protected function set($key, $val){        $this->values[$key]=$val;    }    static function getRequest(){        return self::instance()->get('request');    }    static function setRequest(woo\controller\Request $request){        return self::instance()->set('request', $request);    }}//會話層級的註冊表class SessionRegistry extends Registry{    private static $instance;    private function __construct(){        session_start();    }    //返回唯一執行個體    static function instance(){        if(!isset(self::$instance)){            self::$instance=new self();        }        return self::$instance;    }    protected function get($key){        if( isset($_SESSION[__CLASS__][$key]) ){            return isset($_SESSION[__CLASS__][$key]);        }        return null;    }    protected function set($key, $val){        $_SESSION[__CLASS__][$key]=$val;    }    static function getComplex(){        return self::instance()->get('complex');    }    static function setRequest(woo\controller\Complex $request){        return self::instance()->set('complex', $request);    }}//應用程式層級的註冊表class ApplicationRegistry extends Registry{    private static $instance;    private $freezedir='Data';    private $values=array();    private $mtimes=array();    private function __construct(){        session_start();    }    //返回唯一執行個體    static function instance(){        if(!isset(self::$instance)){            self::$instance=new self();        }        return self::$instance;    }    //get,set都是單獨儲存一個$key到檔案中    protected function get($key){        $path=$this->freezedir.DIRECTORY_SEPARATOR.$key;        if(file_exists($path)){            clearstatcache();            //擷取檔案修改時間            $mtime=filemtime($path);            if(!isset($this->mtimes[$key])){                $this->mtimes[$key]=0;            }            //如果檔案被修改            if($mtime > $this->mtimes[$key]){                $data=file_get_contents($path);                $this->mtimes[$key]=$mtime;                return ($this->values[$key]=unserialize($data));            }        }        if(isset($this->values[$key])){            return $this->values[$key];        }        return null;    }    protected function set($key, $val){        $this->values[$key]=$val;        $path=$this->freezedir.DIRECTORY_SEPARATOR.$key;        //檔案不存在會自動建立        file_put_contents($path, serialize($val));        $this->mtimes[$key]=time();    }    static function getDSN(){        return self::$instance()->get('DSN');    }    static function setDSN($dsn){        return self::$instance()->set('DSN',$dsn);    }}3 前端控制器Controller----結合註冊表模式與命令模式打造統一入口架構<?phpnamespace Woo\Command;include_once("./Woo/Controller/Request.php");//Command類  //* 命令對象擁有獨立處理視圖的功能abstract class Command{    //任何子類都無法覆蓋該方法(永遠無參數)    final function __construct(){}    //該方法傳入一個Request對象,所以擁有訪問請求資料的能力    function execute(\Woo\Controller\Request $request){        //可以做其他事情        //...        //再調用doExecute方法        $this->doExecute($request);    }    function disPlay($request){        //擷取cmd,用於決定調取那個頁面        $cmd=$request->getProperty('cmd');        //寫法不是很好....截取command之前的字元        print $cmd;        $viewUrl="./Woo/View/".substr($cmd,0,strlen($cmd)-(7))."View.html";        include_once($viewUrl);    }    abstract function doExecute(\Woo\Controller\Request $request);} <?phpnamespace Woo\Command;include_once("./Woo/Controller/Request.php");include_once("./Woo/Command/DefaultCommand.php");//CommandResolver 命令解析器class CommandResolver{    private static $base_cmd;    private static $default_cmd;    function __construct(){        if(!self::$base_cmd){            self::$base_cmd=new \ReflectionClass("\Woo\Command\Command");            self::$default_cmd=new DefaultCommand();        }    }    function getCommand(\Woo\Controller\Request $request){        //指定需要調用的Command的key為cmd        $cmd=$request->getProperty('cmd');        $sep=DIRECTORY_SEPARATOR;        //找不到指定cmd資料時,返回預設cmd執行個體        if(!$cmd){            return clone self::$default_cmd;        }        $cmd=str_replace(array('.',$sep), "", $cmd);        $filePath=".\Woo{$sep}Command{$sep}{$cmd}.php";        $className="\Woo\\Command\\{$cmd}";        if(file_exists($filePath)){            require_once("$filePath");            //判斷傳入的類是否存在,是否是base_cmd的子類            if(class_exists($className)){                $cmd_class=new \ReflectionClass($className);                if($cmd_class->isSubclassOf(self::$base_cmd)){                    return $cmd_class->newInstance();                }else{                    //解析失敗,跳轉到預設頁面                    $request->addFeedback("command '$cmd' is not a command");                    return clone self::$default_cmd;                }            }        }else{            $request->addFeedback("command '$cmd' is not found");            return clone self::$default_cmd;        }    }}<?phpnamespace Woo\Command;include_once("./Woo/Controller/Request.php");include_once("./Woo/Command/Command.php");class DefaultCommand extends Command{    function doExecute(\Woo\Controller\Request $request){        $request->addFeedback("Welcome to WOO!");        $feedbacks=$request->getFeedback();        foreach ($feedbacks as $key=>$val){            print $val;            print "<br>";        }        include_once("Woo/View/main.html");    }}<?phpnamespace Woo\Command;include_once("./Woo/Controller/Request.php");include_once("./Woo/Command/Command.php");class MyCommand extends Command{    function doExecute(\Woo\Controller\Request $request){        $request->addFeedback("Welcome to WOO!");        $feedbacks=$request->getFeedback();        foreach ($feedbacks as $key=>$val){            print $val;            print "<br>";        }        $this->disPlay($request);    }}<?phpnamespace Woo\Base;include_once("./Woo/Base/Registry.php");//應用程式層級的註冊表//*DNS Data Source Nameclass ApplicationRegistry extends Registry{    private static $instance;    private $freezedir='./Woo/Cache';    private $values=array();    private $mtimes=array();    private function __construct(){        session_start();    }    //返回唯一執行個體    static function instance(){        if(!isset(self::$instance)){            self::$instance=new self();        }        return self::$instance;    }    //get,set都是單獨儲存一個$key到檔案中    protected function get($key){        $path=$this->freezedir.DIRECTORY_SEPARATOR.$key;        if(file_exists($path)){            clearstatcache();            //擷取檔案修改時間            $mtime=filemtime($path);            if(!isset($this->mtimes[$key])){                $this->mtimes[$key]=0;            }            //如果檔案被修改            if($mtime > $this->mtimes[$key]){                $data=file_get_contents($path);                $this->mtimes[$key]=$mtime;                return ($this->values[$key]=unserialize($data));            }        }        if(isset($this->values[$key])){            return $this->values[$key];        }        return null;    }    protected function set($key, $val){        $this->values[$key]=$val;        $path=$this->freezedir.DIRECTORY_SEPARATOR.$key;        if(!is_dir($this->freezedir)){            mkdir($this->freezedir);        }        //檔案不存在會自動建立        file_put_contents($path, serialize($val));        $this->mtimes[$key]=time();    }    static function getDSN(){        return self::instance()->get('DSN');    }    static function setDSN($dsn){        return self::instance()->set('DSN',$dsn);    }}<?phpnamespace Woo\Base;//建立一個具有範圍的註冊表模式//請求層級註冊表abstract class Registry{    abstract protected function get($key);    abstract protected function set($key,$val);}<?phpnamespace Woo\Base;include_once("./Woo/Base/Registry.php");include_once("./Woo/Controller/Request.php");//請求層級註冊表class RequestRegistry extends Registry{    private $values=array();    private static $instance;    private function __construct(){}    //返回唯一執行個體    static function instance(){        if(!isset(self::$instance)){            self::$instance=new self();        }        return self::$instance;    }    protected function get($key){        if(isset($this->values[$key])){            return isset($this->values[$key]);        }        return null;    }    protected function set($key, $val){        $this->values[$key]=$val;    }    static function getRequest(){        return self::instance()->get('request');    }    static function setRequest(\Woo\Controller\Request $request){        return self::instance()->set('request', $request);    }}<?phpnamespace Woo\Base;include_once("./Woo/Base/Registry.php");//會話層級的註冊表class SessionRegistry extends Registry{    private static $instance;    private function __construct(){        session_start();    }    //返回唯一執行個體    static function instance(){        if(!isset(self::$instance)){            self::$instance=new self();        }        return self::$instance;    }    protected function get($key){        if( isset($_SESSION[__CLASS__][$key]) ){            return isset($_SESSION[__CLASS__][$key]);        }        return null;    }    protected function set($key, $val){        $_SESSION[__CLASS__][$key]=$val;    }    static function getComplex(){        return self::instance()->get('complex');    }    static function setRequest(Woo\Controller\Complex $request){        return self::instance()->set('complex', $request);    }}<?phpnamespace Woo\Controller;include_once("./Woo/Base/ApplicationRegistry.php");//ApplicationHelper 應用助手類--負責讀取設定檔資料,提供給用戶端代碼//*本類利用緩衝機制,提高效能class ApplicationHelper{    private static $instance;    private $config="./Woo/Config/woo_options.xml";    //使用單例模式,用於擷取配置    private function __construct(){}    static function instance(){        if(!self::$instance){            self::$instance=new self();        }        return self::$instance;    }    function init(){        //查看快取資料是否存在        $dsn=\Woo\Base\ApplicationRegistry::getDSN();        if(!is_null($dsn)){            //$dsn不為空白時直接返回            return;        }        $this->getOptions();    }    //只有快取資料不存在時才會調用該方法    private function getOptions(){        $this->ensure(file_exists($this->config),                "Could not find options file!");        $options=simplexml_load_file($this->config);        print get_class($options);        $dsn=$options->dsn;        $this->ensure($dsn, "No DSN found!");        //擷取值之後,將其存放進應用程式層級註冊表中,方便緩衝使用        //先轉化成數組,方便序列化        \Woo\Base\ApplicationRegistry::setDSN(array($dsn->__toString()));        //設定其他值        //...    }    private function ensure($expr,$message){        if(!$expr){            throw new \Exception($message);        }    }}<?phpnamespace Woo\Controller;class Complex{    }<?phpnamespace Woo\Controller;//引入所有需要的檔案include_once("./Woo/Controller/ApplicationHelper.php");include_once("./Woo/Command/CommandResolver.php");include_once("./Woo/Command/Command.php");//Controller類class Controller{    private $applicationHelper;    private function __construct(){}    //該類只能通過run方法獲得執行個體    static function run(){        $instance=new Controller();        //理論上講init只需在應用程式第一次啟動時調用        //(但是PHP屬於解釋型語言,所以每次都必須調用)        $instance->init();        //理論上講handleRequest需要在每次請求到來時運行        $instance->handleRequest();    }    function init(){        //擷取一個單例,用於做全域配置        $applicationHelper=ApplicationHelper::instance();        $applicationHelper->init();    }    //每次請求都需要調用一次    function handleRequest(){        $request=new Request();        $cmd_r=new \Woo\Command\CommandResolver();        //根據request產生對應command抽象類別(介面)的子類執行個體        //之後要利用command執行相關動作        $cmd=$cmd_r->getCommand($request);        $cmd->execute($request);    }}<?phpnamespace Woo\Controller;include_once("./Woo/Base/RequestRegistry.php");//用於儲存需要和視圖層交換的資料class Request{    private $properties;    private $feedback=array();    function __construct(){        $this->init();        \Woo\Base\RequestRegistry::setRequest($this);    }    //同時支援HTTP請求和命令列參數(可用於偵錯工具使用)    //*用於將參數填充進properties屬性裡    function init(){        //表單提交方式        if(isset($_SERVER['REQUEST_METHOD'])){            //用於收集表單提交的資料            $this->properties=$_REQUEST;            return;        }        //$_SERVER['argv'] 傳遞給該指令碼的參數        foreach ($_SERVER['argv'] as $arg){            //搜尋字串第一次出現的位置            if(strpos($arg, '=')){                list($key,$val)=explode("=", $arg);                $this->setProperty($key,$val);            }        }    }    function getProperty($key){        if(isset($this->properties[$key])){            return $this->properties[$key];        }        return null;    }    function setProperty($key,$val){        $this->properties[$key]=$val;    }    function addFeedback($msg){        array_push($this->feedback, $msg);    }    function getFeedback(){        return $this->feedback;    }    function getFeedbackString($separator="\n"){        return implode($separator,$this->feedback);    }}//woo_options.xml<?xml version="1.0" encoding="UTF-8"?><data><dsn>dsn</dsn><dsn2>DSN</dsn2></data> //架構入口index.php<?phpuse Woo\Controller\Controller;include_once("./Woo/Controller/Controller.php");//print_r($_GET);//架構入口Controller::run(); 


八. .PHP模式設計----企業模式(1)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.