Heim Backend-Entwicklung PHP-Tutorial 八. .PHP模式设计企业模式(1)

八. .PHP模式设计企业模式(1)

Jun 23, 2016 pm 01:44 PM


(*暂时未拆分前端控制器和应用控制器,全部集成在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(); 
Nach dem Login kopieren


Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn

Heiße KI -Werkzeuge

Undresser.AI Undress

Undresser.AI Undress

KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover

AI Clothes Remover

Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool

Undress AI Tool

Ausziehbilder kostenlos

Clothoff.io

Clothoff.io

KI-Kleiderentferner

AI Hentai Generator

AI Hentai Generator

Erstellen Sie kostenlos Ai Hentai.

Heißer Artikel

R.E.P.O. Energiekristalle erklärten und was sie tun (gelber Kristall)
2 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌
Repo: Wie man Teamkollegen wiederbelebt
4 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Abenteuer: Wie man riesige Samen bekommt
3 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌

Heiße Werkzeuge

Notepad++7.3.1

Notepad++7.3.1

Einfach zu bedienender und kostenloser Code-Editor

SublimeText3 chinesische Version

SublimeText3 chinesische Version

Chinesische Version, sehr einfach zu bedienen

Senden Sie Studio 13.0.1

Senden Sie Studio 13.0.1

Leistungsstarke integrierte PHP-Entwicklungsumgebung

Dreamweaver CS6

Dreamweaver CS6

Visuelle Webentwicklungstools

SublimeText3 Mac-Version

SublimeText3 Mac-Version

Codebearbeitungssoftware auf Gottesniveau (SublimeText3)

11 beste PHP -URL -Shortener -Skripte (kostenlos und Premium) 11 beste PHP -URL -Shortener -Skripte (kostenlos und Premium) Mar 03, 2025 am 10:49 AM

Lange URLs, die oft mit Schlüsselwörtern und Tracking -Parametern überfüllt sind, können Besucher abschrecken. Ein URL -Verkürzungsskript bietet eine Lösung, die präzise Links erstellt, die ideal für soziale Medien und andere Plattformen sind. Diese Skripte sind für einzelne Websites a wertvoll

Einführung in die Instagram -API Einführung in die Instagram -API Mar 02, 2025 am 09:32 AM

Nach seiner hochkarätigen Akquisition durch Facebook im Jahr 2012 nahm Instagram zwei APIs für den Einsatz von Drittanbietern ein. Dies sind die Instagram -Graph -API und die Instagram Basic Display -API. Ein Entwickler, der eine App erstellt, die Informationen von a benötigt

Arbeiten mit Flash -Sitzungsdaten in Laravel Arbeiten mit Flash -Sitzungsdaten in Laravel Mar 12, 2025 pm 05:08 PM

Laravel vereinfacht die Behandlung von temporären Sitzungsdaten mithilfe seiner intuitiven Flash -Methoden. Dies ist perfekt zum Anzeigen von kurzen Nachrichten, Warnungen oder Benachrichtigungen in Ihrer Anwendung. Die Daten bestehen nur für die nachfolgende Anfrage standardmäßig: $ Anfrage-

Erstellen Sie eine React -App mit einem Laravel -Back -Ende: Teil 2, reagieren Erstellen Sie eine React -App mit einem Laravel -Back -Ende: Teil 2, reagieren Mar 04, 2025 am 09:33 AM

Dies ist der zweite und letzte Teil der Serie zum Aufbau einer Reaktionsanwendung mit einem Laravel-Back-End. Im ersten Teil der Serie haben wir eine erholsame API erstellt, die Laravel für eine grundlegende Produktlistenanwendung unter Verwendung von Laravel erstellt hat. In diesem Tutorial werden wir Dev sein

Vereinfachte HTTP -Reaktion verspottet in Laravel -Tests Vereinfachte HTTP -Reaktion verspottet in Laravel -Tests Mar 12, 2025 pm 05:09 PM

Laravel bietet eine kurze HTTP -Antwortsimulationssyntax und vereinfache HTTP -Interaktionstests. Dieser Ansatz reduziert die Code -Redundanz erheblich, während Ihre Testsimulation intuitiver wird. Die grundlegende Implementierung bietet eine Vielzahl von Verknüpfungen zum Antworttyp: Verwenden Sie Illuminate \ Support \ facades \ http; Http :: fake ([ 'Google.com' => 'Hallo Welt',, 'github.com' => ['foo' => 'bar'], 'Forge.laravel.com' =>

Curl in PHP: So verwenden Sie die PHP -Curl -Erweiterung in REST -APIs Curl in PHP: So verwenden Sie die PHP -Curl -Erweiterung in REST -APIs Mar 14, 2025 am 11:42 AM

Die PHP Client -URL -Erweiterung (CURL) ist ein leistungsstarkes Tool für Entwickler, das eine nahtlose Interaktion mit Remote -Servern und REST -APIs ermöglicht. Durch die Nutzung von Libcurl, einer angesehenen Bibliothek mit Multi-Protokoll-Dateien, erleichtert PHP Curl effiziente Execu

12 Beste PHP -Chat -Skripte auf Codecanyon 12 Beste PHP -Chat -Skripte auf Codecanyon Mar 13, 2025 pm 12:08 PM

Möchten Sie den dringlichsten Problemen Ihrer Kunden in Echtzeit und Sofortlösungen anbieten? Mit Live-Chat können Sie Echtzeitgespräche mit Kunden führen und ihre Probleme sofort lösen. Sie ermöglichen es Ihnen, Ihrem Brauch einen schnelleren Service zu bieten

Ankündigung von 2025 PHP Situation Survey Ankündigung von 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

Die 2025 PHP Landscape Survey untersucht die aktuellen PHP -Entwicklungstrends. Es untersucht Framework -Nutzung, Bereitstellungsmethoden und Herausforderungen, die darauf abzielen, Entwicklern und Unternehmen Einblicke zu geben. Die Umfrage erwartet das Wachstum der modernen PHP -Versio

See all articles