Home php教程 php手册 Zend Framework框架路由机制代码分析

Zend Framework框架路由机制代码分析

Jun 06, 2016 pm 07:32 PM
framework zend code analyze mechanism frame routing

本文分析了Zend Framework框架路由机制代码。分享给大家供大家参考,具体如下: 在框架中,有关路由的调用关系为: 1、apache的mod_rewrite模块把请求路由到框架的启动脚本,一般是index.php; 2、前端控制器Zend_Controller_Front通过dispatch函数进行请求

本文分析了Zend Framework框架路由机制代码。分享给大家供大家参考,具体如下:

在框架中,有关路由的调用关系为:

1、apache的mod_rewrite模块把请求路由到框架的启动脚本,一般是index.php;

2、前端控制器Zend_Controller_Front通过dispatch函数进行请求分发;

3、路由器Zend_Controller_Router_Rewrite通过route函数处理路由,对路由器中已有的路由规则,按照加入顺序的逆序(类似于栈,后进先出)对每个route调用match函数,以检查请求是否和当前路由规则匹配,如果匹配的话把路由器的当前路由这个变量($_currentRoute)设置为匹配的路由,并把route解析出来的参数传给Zend_Controller_Request_Http对象,到这里完成路由设置。

如果没有发现路由,框架会使用Index控制器的index这个action。

对Zend_Controller_Router_Route中的函数代码分析:

1、构造函数

public function __construct($route, $defaults = array(), $reqs = array())
{
  $route = trim($route, $this->_urlDelimiter); //去掉规则首尾的url分隔符(默认是/)
  $this->_defaults = (array) $defaults; //默认值数组,以变量名为键
  $this->_requirements = (array) $reqs; //变量需要满足的正则表达式,以变量名为键
  if ($route != '') {
   foreach (explode($this->_urlDelimiter, $route) as $pos => $part) {
    //把规则切分为一个数组
    if (substr($part, 0, 1) == $this->_urlVariable) {//如果是一个变量的定义
     $name = substr($part, 1); //获取变量名
     //如果该变量定义了对应的正则表达式,则获取该表达式,否则置为null
     $regex = (isset($reqs[$name]) ? $reqs[$name] : $this->_defaultRegex);
     //_parts数组包含了规则的各个部分,如果是变量的话,数组中有name元素
     $this->_parts[$pos] = array('name' => $name, 'regex' => $regex);
     //_vars包含了该规则中的所有变量的名字
     $this->_vars[] = $name;
    } else { //普通字符串
     $this->_parts[$pos] = array('regex' => $part);
     if ($part != '*') {
      $this->_staticCount++; //该规则的普通字符串的个数
     }
    }
   }
  }
}

Copy after login

2、匹配算法

public function match($path)
{
  $pathStaticCount = 0;
  $defaults = $this->_defaults; //默认值数组,数组元素的键值是变量名
   //默认值数组的一个拷贝,不过变量的值全部换成布尔值,其实这个值并没有实际用处,下面程序仅仅
  //是通过判断键值是否存在而确定是否包含一个变量,可能这么做是为了节省空间,不过要是这样的话
  //不如直接使用 $this->_defaults了?
  if (count($defaults)) {
   $unique = array_combine(array_keys($defaults), array_fill(0, count($defaults), true));
  } else {
   $unique = array();
  }
  $path = trim($path, $this->_urlDelimiter); //传入的path是已经去掉baseUrl的,这里确保去掉首尾的分隔符
  if ($path != '') {
   $path = explode($this->_urlDelimiter, $path);
   foreach ($path as $pos => $pathPart) {
    if (!isset($this->_parts[$pos])) {
     //把path根据url分隔符分割为数组后,把每一部分和规则的对应部分比较,如果path中存在,
     //而规则中不存在对应部分,那么该规则肯定不匹配,这里要注意$pos,是通过它把规则
     //和path的对应部分对应起来。
     return false;
    }
    if ($this->_parts[$pos]['regex'] == '*') {
      //如果规则的当前部分是通配符*,则把path的剩余部分解释为url传递过来的变量,他们按照
     //“变量名/变量值”这样的形式成对出现
     $parts = array_slice($path, $pos); //获取path的剩余部分
     $this->_getWildcardData($parts, $unique);
     break;
    }
    $part = $this->_parts[$pos];
    $name = isset($part['name']) ? $part['name'] : null;
    $pathPart = urldecode($pathPart);//对传过来的值进行解码
    if ($name === null) {//普通字符串,和规则的对应部分比较是否相等即可
     if ($part['regex'] != $pathPart) {
      return false;
     }
    } elseif ($part['regex'] === null) {
      //如果是变量,但是没有需要满足的正则表达式,那么只有值不为空就可以了
     if (strlen($pathPart) == 0) {
      return false;
     }
    } else {//如果对该变量需要满足一个正则表达式,那么这里进行验证
     $regex = $this->_regexDelimiter . '^' . $part['regex'] . '$' . $this->_regexDelimiter . 'iu';
     if (!preg_match($regex, $pathPart)) {
      return false;
     }
    }
    if ($name !== null) {
     // 如果是一个变量,则设置变量的值
     $this->_values[$name] = $pathPart;
     $unique[$name] = true; //其实没有必要设置,这个版本根本就没有用它
    } else {
     //把普通字符串的匹配计数加1,因为规则中的普通字符串是必须在path中存在的,否则就是
     //匹配失败
     $pathStaticCount++;
    }
   }
  }
   //$this->_values中保存的是分析获取的变量,如果规则中存在‘*',则$this->_params是获取的
  //变量,否则是空数组,$this->_defaults是规则提供的默认变量值,这里用‘+'把三个数组相加
  //这样的好处是如果后面的数组与前面的数组有相同的非整数的键值,后面的不会覆盖前面的,这
  //与array_merge函数有区别,后者是会覆盖的。也就是说,如果$this->_values 中已经有键controller
  //,那么$this->_defaults中的controller元素就被忽略,这样就$this->_defaults中的默认值只有在path
  //中不存在的时候才会出现在返回值中。
  $return = $this->_values + $this->_params + $this->_defaults;
  // Check if all static mappings have been met
  if ($this->_staticCount != $pathStaticCount) {//规则的所有普通字符串必须在path中得到匹配
   return false;
  }
  // 解析完后,规则定义的所有变量也必须全部出现,否则视为不匹配
  foreach ($this->_vars as $var) {
   if (!array_key_exists($var, $return)) {
    return false;
   }
  }
  return $return;
}

Copy after login

更多关于zend相关内容感兴趣的读者可查看本站专题:《Zend FrameWork框架入门教程》、《php优秀开发框架总结》、《Yii框架入门及常用技巧总结》、《ThinkPHP入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于Zend Framework框架的PHP程序设计有所帮助。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to evaluate the cost-effectiveness of commercial support for Java frameworks How to evaluate the cost-effectiveness of commercial support for Java frameworks Jun 05, 2024 pm 05:25 PM

Evaluating the cost/performance of commercial support for a Java framework involves the following steps: Determine the required level of assurance and service level agreement (SLA) guarantees. The experience and expertise of the research support team. Consider additional services such as upgrades, troubleshooting, and performance optimization. Weigh business support costs against risk mitigation and increased efficiency.

Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Jun 12, 2024 pm 08:38 PM

Since the launch of ChatGLM-6B on March 14, 2023, the GLM series models have received widespread attention and recognition. Especially after ChatGLM3-6B was open sourced, developers are full of expectations for the fourth-generation model launched by Zhipu AI. This expectation has finally been fully satisfied with the release of GLM-4-9B. The birth of GLM-4-9B In order to give small models (10B and below) more powerful capabilities, the GLM technical team launched this new fourth-generation GLM series open source model: GLM-4-9B after nearly half a year of exploration. This model greatly compresses the model size while ensuring accuracy, and has faster inference speed and higher efficiency. The GLM technical team’s exploration has not

How does the learning curve of PHP frameworks compare to other language frameworks? How does the learning curve of PHP frameworks compare to other language frameworks? Jun 06, 2024 pm 12:41 PM

The learning curve of a PHP framework depends on language proficiency, framework complexity, documentation quality, and community support. The learning curve of PHP frameworks is higher when compared to Python frameworks and lower when compared to Ruby frameworks. Compared to Java frameworks, PHP frameworks have a moderate learning curve but a shorter time to get started.

How do the lightweight options of PHP frameworks affect application performance? How do the lightweight options of PHP frameworks affect application performance? Jun 06, 2024 am 10:53 AM

The lightweight PHP framework improves application performance through small size and low resource consumption. Its features include: small size, fast startup, low memory usage, improved response speed and throughput, and reduced resource consumption. Practical case: SlimFramework creates REST API, only 500KB, high responsiveness and high throughput

The Mistral open source code model takes the throne! Codestral is crazy about training in over 80 languages, and domestic Tongyi developers are asking to participate! The Mistral open source code model takes the throne! Codestral is crazy about training in over 80 languages, and domestic Tongyi developers are asking to participate! Jun 08, 2024 pm 09:55 PM

Produced by 51CTO technology stack (WeChat ID: blog51cto) Mistral released its first code model Codestral-22B! What’s crazy about this model is not only that it’s trained on over 80 programming languages, including Swift, etc. that many code models ignore. Their speeds are not exactly the same. It is required to write a "publish/subscribe" system using Go language. The GPT-4o here is being output, and Codestral is handing in the paper so fast that it’s hard to see! Since the model has just been launched, it has not yet been publicly tested. But according to the person in charge of Mistral, Codestral is currently the best-performing open source code model. Friends who are interested in the picture can move to: - Hug the face: https

Golang framework documentation best practices Golang framework documentation best practices Jun 04, 2024 pm 05:00 PM

Writing clear and comprehensive documentation is crucial for the Golang framework. Best practices include following an established documentation style, such as Google's Go Coding Style Guide. Use a clear organizational structure, including headings, subheadings, and lists, and provide navigation. Provides comprehensive and accurate information, including getting started guides, API references, and concepts. Use code examples to illustrate concepts and usage. Keep documentation updated, track changes and document new features. Provide support and community resources such as GitHub issues and forums. Create practical examples, such as API documentation.

How to choose the best golang framework for different application scenarios How to choose the best golang framework for different application scenarios Jun 05, 2024 pm 04:05 PM

Choose the best Go framework based on application scenarios: consider application type, language features, performance requirements, and ecosystem. Common Go frameworks: Gin (Web application), Echo (Web service), Fiber (high throughput), gorm (ORM), fasthttp (speed). Practical case: building REST API (Fiber) and interacting with the database (gorm). Choose a framework: choose fasthttp for key performance, Gin/Echo for flexible web applications, and gorm for database interaction.

Detailed practical explanation of golang framework development: Questions and Answers Detailed practical explanation of golang framework development: Questions and Answers Jun 06, 2024 am 10:57 AM

In Go framework development, common challenges and their solutions are: Error handling: Use the errors package for management, and use middleware to centrally handle errors. Authentication and authorization: Integrate third-party libraries and create custom middleware to check credentials. Concurrency processing: Use goroutines, mutexes, and channels to control resource access. Unit testing: Use gotest packages, mocks, and stubs for isolation, and code coverage tools to ensure sufficiency. Deployment and monitoring: Use Docker containers to package deployments, set up data backups, and track performance and errors with logging and monitoring tools.

See all articles