• php前端控制器设计1


    The primary role of a front controller in web-based applications is to encapsulate the typical request/route/dispatch/response cycles inside the boundaries of an easily-consumable API, which is exactly what the web server does. Indeed the process seems redundant at first blush咋一看, but when coupled to an MVC implementation, we’re actually trying to build up a controller that in turn controls other controllers.

    Despite the apparent duplication of roles, the implementation of a front controller emerges as a response to the growing complexities of modern web application development. Tunneling all requests through a single entry point is certainly an efficient way to implement a command-based mechanism, which not only allows you to route and dispatch commands to appropriate handlers, but also exposes a flexible structure that can be massaged and scaled without much burden.

    尽管角色看起来有点多余,但是前端控制器是现代web应用陈旭复杂性渐增的产物。通过单一的入口来处理所有的请求,是一个实现command-base 机制的高效方式,它不仅允许你route和分发命令道合适的处理者,同时显示了一个灵活的结构。

    Frankly speaking, front controllers are easily-tameable可驯服的 可驯养的 

    creatures. (意思是非常简单)In the simplest scenario, a naive combination of URL rewriting along with a few switch statements is all we need to route and dispatch requests, though in production(在生产中) it might be necessary to appeal to more complex and granular粒状的 implementations, especially if we want to distill routing and dispatching processes through finer-grained 细粒度objects armed with well-segregated responsibilities.

    In this two-part article I’ll be exploring in depth a couple of straightforward approaches that you might find appealing, especially if you’re trying to implement an expandable front controller from scratch without sweating excessively(不要出汗过多,即简单) during the process or having to cope with the burdens of a bloated framework.

    Routing and Dispatching in a Straightforward Way

    In reality, there are so many nifty俏皮的;漂亮的 options that can be used for building a functional front controller, but I’ll start by letting my pragmatic side 务实的一面show (yes, I have one). The first front controller implementation that I’ll go through will be charged with routing/dispatching URIs that conform to the following format:

    basepath/controllername/actionname/param1/param2/.../paramN

    If you’ve ever laid your hands on a framework that uses the notion of parameterized action controllers, the above URI should familiar to you. It is a fairly ubiquitous pattern. Of course, the most challenging task here is designing a flexible mechanism capable of parsing the URIs in question without much fuss. This can be achieved in all sort of creative ways, either by plain procedural code or appealing to object-oriented code. I’ll be encapsulating the nuts and bolts of the routing/dispatching logic beneath the shell of a single class:

    最后挑战的工作是解析url,我们把route/dispatch放在一个类中:

    <?php
    namespace LibraryController;
    
    interface FrontControllerInterface
    {
        public function setController($controller);
        public function setAction($action);
        public function setParams(array $params);
        public function run();
    }
    <?php
    namespace LibraryController;
    
    class FrontController implements FrontControllerInterface
    {
        const DEFAULT_CONTROLLER = "IndexController";
        const DEFAULT_ACTION     = "index";
        
        protected $controller    = self::DEFAULT_CONTROLLER;
        protected $action        = self::DEFAULT_ACTION;
        protected $params        = array();
        protected $basePath      = "mybasepath/";
        
        public function __construct(array $options = array()) { //$options前面有一个array显示表示是array,没有也可以
            if (empty($options)) {
               $this->parseUri();
            }
            else {
                if (isset($options["controller"])) {
                    $this->setController($options["controller"]);
                }
                if (isset($options["action"])) {
                    $this->setAction($options["action"]);     
                }
                if (isset($options["params"])) {
                    $this->setParams($options["params"]);
                }
            }
        }
        
        protected function parseUri() {
            $path = trim(parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH), "/");
            $path = preg_replace('/[^a-zA-Z0-9]//', "", $path);
            if (strpos($path, $this->basePath) === 0) {
                $path = substr($path, strlen($this->basePath));
            }
            @list($controller, $action, $params) = explode("/", $path, 3);
            if (isset($controller)) {
                $this->setController($controller);
            }
            if (isset($action)) {
                $this->setAction($action);
            }
            if (isset($params)) {
                $this->setParams(explode("/", $params));
            }
        }
        
        public function setController($controller) {
            $controller = ucfirst(strtolower($controller)) . "Controller";
            if (!class_exists($controller)) {
                throw new InvalidArgumentException(
                    "The action controller '$controller' has not been defined.");
            }
            $this->controller = $controller;
            return $this;
        }
        
        public function setAction($action) {
            $reflector = new ReflectionClass($this->controller);
            if (!$reflector->hasMethod($action)) {
                throw new InvalidArgumentException(
                    "The controller action '$action' has been not defined.");
            }
            $this->action = $action;
            return $this;
        }
        
        public function setParams(array $params) {
            $this->params = $params;
            return $this;
        }
        
        public function run() {
            call_user_func_array(array(new $this->controller, $this->action), $this->params);
        }
    }

    $path = trim(parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH), "/");

    把url的path前面/去掉。

    然后用正则:

    $path = preg_replace('/[^a-zA-Z0-9]//'""$path);

    再把无效字符替换为空。

    if (strpos($path, $this->basePath) === 0) {
    $path = substr($path, strlen($this->basePath));
    }

    strpos寻找当前路径是否以basePath开头,(一定要用===判断,因为如果没有找到该字符串,则返回 false,用==0也是相等的)。

    如果以basePath开头,则取后面的字串。

    下面颜色上面几句话作用:

    $url='http://localhost/php/controller/action/param1/param2';
    $path = trim(parse_url($url, PHP_URL_PATH), "/"); // php/controller/action/param1/param2
    print $path.'<br/>';  //php/pattern/parseUrL.php/controller/action/param1/param2
    $path = preg_replace('/[^a-zA-Z0-9]//', "", $path); //php/controller/action/param1/param2
    print $path.'<br/>'; //php/pattern/parseUrL.php/controller/action/param1/param2
    $basePath='php/'; //最开始后面没有带/,导致错误.
    if (strpos($path,$basePath) === 0) {
    $path = substr($path, strlen($basePath));
    }
    print $path.'<br/>';///controller/action/param1/param2

     @list($controller, $action, $params) = explode("/", $path, 3);分解url。

    array explode ( string $delimiter , string $string [, int $limit ] ) 最后一个参数现在分解的大小。

    3说明我们最多分成3段。结果:

    controller
    action
    param1/param2

    为什么要用@。

    当参数少时。

    $arr=array(1,2);
    list($a)=$arr;

    print $a,等于1.

    当参数不足时。

    $arr=array(1,2);
    list($a,$b,$c)=$arr;
    echo $a,$b,$c;

    Notice: Undefined offset: 2 in F:xampphtdocsphppatternparseUrL.php on line 48
    1,2 

    可以看到,产生错误信息,$a=1,$b=2;$c没有值,用@就看不到错误信息了。

    判断controller是否存在使用了

    bool class_exists ( string $class_name [, bool $autoload = true ] )

    这个函数

    默认回调用默认调用 __autoload。载入类。

    if (!class_exists($controller)) {
    throw new InvalidArgumentException(
    "The action controller '$controller' has not been defined.");
    }

    InvalidArgumentException

    Exception thrown if an argument does not match with the expected value.

    当参数不满足期待的值我们都可以throw这个异常。

    检查action:

     public function setAction($action) {
            $reflector = new ReflectionClass($this->controller);
            if (!$reflector->hasMethod($action)) {
                throw new InvalidArgumentException(
                    "The controller action '$action' has been not defined.");
            }
            $this->action = $action;
            return $this;
        }

    用到了反射。

    参数没有做过多检查:

      public function setParams(array $params) {
            $this->params = $params;
            return $this;
        }

    注意这个是怎么调用的:

     if (isset($params)) {            $this->setParams(explode("/", $params));        }

    $params变成了array(param1,param2).

    最后run函数;

     public function run() {
            call_user_func_array(array(new $this->controller, $this->action), $this->params);
        }

    可以参考我以前写的文章http://www.cnblogs.com/youxin/p/3150314.html。

    The FrontController class’ duties boil down to parsing the request URI, or eventually assembling a brand new one from scratch through a few basic mutators. Once this task has been carried out, the run() method neatly dispatches the request to the appropriate action controller, along with the supplied arguments, if any.

    Given its minimal API, consuming the class is a simple two-step process. First, drop into the web root a typical .htaccess file, like this one:

    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /index.php
    上面的写法有错误,index.php前面应该没有/,因为现在已经在该目录下了,如果写了会产生找不到文件错误。

    rewrite参考以前写的:http://www.cnblogs.com/youxin/p/3150235.html

    Second, set up the following code snippet as index.php:

    <?php
    use LibraryLoaderAutoloader,
        LibraryControllerFrontController;
        
    require_once __DIR__ . "/Library/Loader/Autoloader.php";
    $autoloader = new Autoloader;
    $autoloader->register();
    
    $frontController = new FrontController();
    $frontController->run();

    In this case, the controller simply parses the request URI and feeds it to the given action controller, which is its default behavior by the way. It’s feasible, though, to explicitly provide a URI by calling the corresponding setters, as follows:

    <?php
    $frontController = new FrontController(array(
        "controller" => "test", 
        "action"     => "show", 
        "params"     => array(1)
    ));
    
    $frontController->run();

    The front controller here is pretty malleable, easily configurable either for internally parsing requests or for routing/dispatching custom ones supplied directly from client code. Moreover, the previous example shows in a nutshell how to call the show() method of an hypotheticalTestController class and pass around a single numeric argument to it. Of course, it’s possible to use different URIs at will and play around with the controller’s abilities. Therefore, if you’re bored and want to have some fun for free, just go ahead and do so.

    Though I have to admit that my carefully-crafted FrontController class has pretty limited functionality, it makes a statement on its own. It demonstrates that building up a customizable front controller is in fact a straightforward process that can be tamed successfully without having to use obscure and tangled programming principles.

    On the flip side, the bad news is that the class has way to many responsibilities to watch over. If you’re skeptical, just check out its run() method. Certainly its implementation is clean and compact, and can be even accommodated to intercept pre/post dispatch hooks. But it does multiple things at the same time and behaves pretty much as a catch-all point for routes and dispatches. It’s preferable to have a front controller dissected in more granular classes, whose responsibilities are narrowed to perform discrete tasks.

    Needless to say that getting such a distilled front controller up and running as expected requires traveling down the road to a fairly prolific number of classes and interfaces. I’m reluctant to make this installment excessively lengthy, so I’ll be covering in depth the details of the whole implementation process in the next article. This way you can have some time to twist and bend my sample front controller and make it suit the taste of your delicate palate.

    Closing Thoughts

    Front controllers are ridiculously simple to implement from scratch, regardless if the approach makes use of procedural code or object-oriented code. And because of its easy-going nature, it’s fairly easy to scale up a naïve, primitive front controller and pitch over its shoulders the whole shebang required for handling RESTful resources behind the scenes.

    Quite possibly, the most tangled aspect of writing a front controller is solving the implicit dilemma困境

    when it comes to deciding if the requests must be either statically or dynamically routed and dispatched to the appropriate handlers. There’s no formal principle that prescribes规定 all the routing/dispatching logic should be encapsulated within the controller’s boundaries or broken down into standalone modules that can be reused independently.

    Precisely, the latter is the form of implementation that I’ll be discussing over the course of the next article. So, stay tuned!

     转自:http://phpmaster.com/front-controller-pattern-1/

  • 相关阅读:
    uva 11995 I Can Guess the Data Structure!
    poj 1981 Circle and Points
    hdoj 2149 Public Sale
    hdoj 2188 悼念512汶川大地震遇难同胞——选拔志愿者
    hdoj 1846 Brave Game
    vue 细节注意
    meta标签设置不缓存
    -webkit-overflow-scrolling
    ios上表单默认样式
    vue-cli项目上传到github预览问题
  • 原文地址:https://www.cnblogs.com/youxin/p/3248714.html
Copyright © 2020-2023  润新知