Making PATHINFO Mode Function Similar to ThinkPHP Framework (2)

Keywords: PHP Apache REST Linux

From the last release< Making PATHINFO Mode Function Similar to ThinkPHP Framework (Article address: http://www.cnblogs.com/phpstudy2015-6/p/6242700.html ) It's been many days, so let's finish the rest tonight.

The previous article has implemented the PATHINFO mode URL, that is, when we visit the site built by MVC mode, we only need to add (/module/controller/action) after the domain name, which is very intelligent. And through the automatic trigger function of new Object, class files can be loaded automatically, so as long as we build the basic framework, we can not worry about the file access path, of course, the premise is to have a reasonable and regular naming method.

I. Achieving the Goals of this Article

The last article has achieved specific functions, so what should I write this time? Is there anything else to pay attention to?

As a programmer ape, it's essential for me to study hard, so this time I'm going to transform my last article into a file-saved version, where regular rules in $routes are stored in a file, and then get Route out when it needs to be used. Then we test the efficiency of apache and its ab pressure.

II. Core Knowledge

This article does not cover much core knowledge.

1. Save and fetch files. This time I use file_put_contents() and file_get_contents(). Of course, there's still a lot to choose from.

2. Before saving and retrieving files, of course, serialize and deserialize them. The functions used are serialize() and unserialize().

3. The ab concurrency test of apache. (Concurrent testing of this high-level gadget, just contact is not very familiar with this piece of buddy, if allowed, please give some suggestions to the younger brother)

III. Environmental Description

Linux Virtual Machine, PHP 5.3.6, Domain Name www.test2.com

4. Code examples

/Framework/Core/Url2.class.php

  1 <?php
  2 /*
  3 *@Maker: One Leaf Follows the Wind
  4 *@Blog: http://www.cnblogs.com/phpstudy 2015-6/
  5 *@Time: 2017.1.10
  6 *@Version: File saved version
  7 */
  8 class Url2
  9 {
 10     //Define regular expression constants
 11     const REGEX_ANY="([^/]+?)";                   #wrong/Any arbitrary character at the beginning
 12     const REGEx_INT="([0-9]+?)";                  #number
 13     const REGEX_ALPHA="([a-zA-Z_-]+?)";           #Letter
 14     const REGEX_ALPHANUMERIC="([0-9a-zA-Z_-]+?)"; #Any alphanumeric number_-
 15     const REGEX_STATIC="%s";                      #placeholder
 16     const ANY="(/[^/]+?)*";                       #Arbitrarily non/Beginning character
 17 
 18     #File-saving
 19     public function addRoute($route,$int)
 20     {
 21         if($int==1)
 22         {
 23             $routes=file_get_contents('./routes.txt');
 24             $routes=unserialize($routes);
 25         }
 26         $routes[]=$this->_ParseRoute($route);
 27         $routes=serialize($routes);
 28         file_put_contents('./routes.txt', $routes);
 29     }
 30     
 31 
 32     /*private
 33       @input :$route Input routing rules
 34       @output:return Return Routing Regular Rules
 35     */
 36     private function _ParseRoute($route)
 37     {
 38         
 39         $parts=explode("/", $route);  #Decomposition of routing rules
 40         $regex="@^";  #Start splicing regular routing rules
 41         if(!$parts[0])
 42         {
 43             array_shift($parts);  #Remove the first empty element
 44         }
 45         foreach ($parts as $part) 
 46         {
 47             $regex.="/";
 48             $args=explode(":",$part);
 49             if(!sizeof($args)==2)
 50             {
 51                 continue;
 52             }
 53             $type=array_shift($args);
 54             $key=array_shift($args);
 55             $this->_normalize($key);  #Standardize parameters and exclude other illegal symbols
 56             $regex.='(?P<'.$key.'>';    #For the back preg_match Regular Matching for Paving the Ground
 57             switch (strtolower($type)) 
 58             {
 59                 case 'int':      #Pure number
 60                     $regex.=self::REGEX_INT;
 61                     break;
 62                 case 'alpha':    #Pure letters
 63                     $regex.=self::REGEX_ALPHA;
 64                     break;
 65                 case 'alphanum':  #Alphanumeric number
 66                     $regex.=self::REGEX_ALPHANUMBERIC;
 67                     break;
 68                 default:
 69                     $regex.=$type; #Custom regular expressions
 70                     break;
 71             }
 72             $regex.=")";
 73         }
 74         $regex.=self::ANY;   #Other URL parameter
 75         $regex.='$@u';
 76         return $regex;
 77     }
 78 
 79     /*public,Match the input URL with the defined regular expression
 80       @input  :$request Input URL
 81       @output :return If successful, output rule array data fail to output false
 82     */
 83     public function getRoute($request)
 84     {
 85         #Handle request,Processing parameters,insufficient M,C,A,Then auto-complement home,index,index,Namely construction MVC structure URL
 86         $request=rtrim($request,'/');           #Remove the excess slash on the right/
 87         $arguments=explode('/',$request);
 88         $arguments=array_filter($arguments);    #Remove empty elements from arrays
 89         $long=sizeof($arguments);               #Number of arrays
 90         switch ($long)                          #Judgement number,Not enough is enough.
 91         {
 92             case '0':
 93                 $request='/home/index/index';
 94                 break;
 95             case '1':
 96                 $request.='/index/index';
 97                 break;
 98             case '2':
 99                 $request.='/index';
100                 break;
101         }       
102         $matches=array();                       #Define an array of matched storage
103         $temp=array();                          #Intermediate cache array
104 
105         #File-saving
106         $routes=file_get_contents('./routes.txt');
107         $routes=unserialize($routes);  
108         foreach ($routes as $v)                 #Start matching
109         {
110             preg_match($v, $request, $temp);    #You need to focus on understanding this array
111             $temp?$matches=$temp:'';
112         }
113         if($matches)                            #judge $matches Is there any data?,No return false
114         {
115             foreach ($matches as $key => $value) #screen
116             {
117                 if(is_int($key))
118                 {
119                     unset($matches[$key]);      #Remove figures key element,Retain the associated elements. And above preg_match Understanding together
120                 }
121             }
122             $result=$matches;
123             if($long > sizeof($result))         #URL Processing after parameter exceeding
124             {
125                 $i=1;
126                 foreach ($arguments as $k => $v) 
127                 {                      
128                     if($k > sizeof($result))
129                     {
130                         if($i==1)
131                         {
132                             $result[$v]='';
133                             $temp=$v;
134                             $i=2;
135                         }
136                         else
137                         {
138                             $result[$temp]=$v;
139                             $i=1;
140                         }                           
141                     }
142                 }
143             }
144             return $result;
145         }
146         return false;
147     }
148     #To standardize parameters, there can be no symbols, only symbols. a-zA-Z0-9 combination
149     private function _normalize(&$param)
150     {
151         $param=preg_replace("/[^a-zA-Z0-9]/", '', $param);
152     }
153 }
154 /*Use examples:
155 #1,Preservation is positive.
156 Load this class of files
157 include './Url.class.php';
158 $router=new Url();
159 $router->addRoute("/alpha:module/alpha:controller/[0-9]+?:a1a",0);  #0 Represents all contents in the empty file and saves them from scratch
160 $router->addRoute("/alpha:module/alpha:controller/alpha:action",1); #1 Represents adding regular rules after a file
161 $router->addRoute("/alpha:module/alpha:controller/alpha:action/(www[0-9]+?):id",1);
162 #2,Comment on the opening access above
163 include './Url.class.php';
164 $router=new Url();
165 $url=$_SERVER['REQUEST_URI'];
166 $urls=$router->getRoute($url); 
167 echo "<pre>";
168 print_r($urls);
169 echo "</pre>";die;
170 */
171 ?>

The above is a modified class file. There are three main changes.

1. Remove the original definition of $routes (protected $routes=array()). Because this definition has any meaning after the file is saved.

2. The method addRoute() is greatly modified. The following picture:

Changed to:

3. Where getRoute() removes regular rules

Changed to:

 

Start visiting:

1. Deposit Rules

index.php

1 <?php
2 include './Framework/Core/Core.php';
3 #The first step is to preserve regular rules
4 $router=new Url2();
5 $router->addRoute("/alpha:module/alpha:controller/[0-9]+?:a1a",0);
6 $router->addRoute("/alpha:module/alpha:controller/alpha:action",1); 
7 $router->addRoute("/alpha:module/alpha:controller/alpha:action/(www[0-9]+?):id",1);

Visit: www.test2.com

Generate routes.txt in the root directory immediately

vi contains serialized content

 

2. Official visit

The index.php file is changed as follows

 1 <?php
 2 include './Framework/Core/Core.php';
 3 
 4 $router=new Url2();
 5 $url=$_SERVER['REQUEST_URI'];
 6 $urls=$router->getRoute($url); 
 7 $_GET['urls']=$urls;
 8 $m=$urls['module'];
 9 $c=$urls['controller'];
10 $a=$urls['action'];
11 if($m&&$c)
12 {
13     $autoload=new Autoload($m,$c);
14     $autoload->putFile();
15 }
16 $object=new $c;
17 $object->$a();
18 
19 ?>

Visit: http://www.test2.com/Home/Test/action/

The results are as follows:

Successful change!

V. Both Stress Tests

apache's ab was used to test the stress of both. (I tested it with apache ab on Windows)

There are many parameters in ab. Here we mainly use - c and - n.

- c: Number of requests generated at a time

- n: Number of requests executed in the test session

ab performance indicators:

1. Throughput (Requests per second)

Quantitative description of server concurrent processing capacity is reqs/s, which refers to the number of requests processed per unit time under a certain number of concurrent users. The maximum number of requests that can be processed per unit time under the number of concurrent users is called maximum throughput. Throughput is based on the number of concurrent users, so the throughput is generally different for different concurrent users.

Calculating formula: total number of requests / time spent processing these requests, that is, Request per second=Complete requests/Time taken for tests

Note: This value represents the overall performance of the current machine. The larger the value, the better.

2. Concurrency Level

3. Average Time per request

Calculating formula: The time spent in processing all requests /(total number of requests/concurrent users), i.e. Time per request=Time taken for tests /(Complete requests/Concurrency Level)

4. Average server request waiting time (Time per request:across all concurrent requests)

Calculating formula: The time/total number of requests taken to complete all requests, i.e. Time taken for/testsComplete requests

 

Test path: http://www.test2.com/Home/Test/action/var1/vaule1/var2/value2

-n 2000 -50 

Perform 2000 requests, using up to 50 concurrent connections

First, test the first (non-file version):

The results are as follows:

2. Testing the second version (file storage):

The results are as follows:

Comparing the above two test data, the results show that the data are very close.

I have changed the parameters of - n and - c var/value and carried out many stress tests. The final results show that the throughput, number of concurrent users, average request waiting time of users, average request waiting time of servers and other data of these two types of files are almost the same, that is, the efficiency performance of the two types of files is similar.

 

(The above are some of my own opinions. If there are any shortcomings or mistakes, please point them out.)

Author: One leaf follows the wind

Statement: This blog article is original, only on behalf of my own views or conclusions summarized during a certain period of work and study. When reproducing, please give a link to the original text in a clear place on the article page.

Posted by scarhand on Thu, 21 Mar 2019 01:36:52 -0700