Home>

Why do we use routing?Reason 1:a more beautiful uri

1.uri improvement

When we first started learning PHP, we must have written uri like blog.php?id=1, and used the get method to get parameters.Such a uri has two disadvantages,One is easy to be attacked by SQL injection.The second is poor maintainability and readability.You can compare which of the following two types of uri is more readable.

www.mysite.com/blog.php?id=1

The uri above is the most commonly used by us to learn PHP.

www.mysite.com/blog/1

This kind of uri is currently the most popular uri, for example,For example, many booksMovie sites,All use such uri, this uri is much simpler than index.php&a =&b=2&c=3&d=4 ....

2. Implementation method

Write one in the root directory of the web project.htaccess file

rewriteengine on
rewriterule ^ ([a-za-z0-9 /] *) $index.php/$1

Rewrite rules,Let the string behind the domain name be directly passed to index.php as a parameter, so index.php becomes the center of your entire web application.Defines "mapping of requests and responses".

Reason 2:easy maintenance of single entry mechanism

Route array

A PHP beginner, just starting a project,The project is doing bigger and bigger,Often this php page passes values ​​to another php page using the get method,Sometimes more than one value is passed,For a long time,Your web project, n php pages is like a complex spider web,Makes it difficult to maintain.Once modified,Will involve a lot of php files, a lot of work.

mvc's single entry mechanism can solve the problem of difficult maintenance,A route is a set of mappings.Allows you to map a method to a uri.

$route=[
  "" =>"[email protected]",  "blog" =>"[email protected]",  "blog/{id}/{name}" =>"[email protected]",];

2. Get parameters

$path=$_ server ["path_info"];
$path=ltrim ($path, "/");
echo $path.php_eol;

After we enter:www.mysite.com/blog/1 in the browser, the path variable is/blog/1. Use the ltrim function to remove the left slash,Then use explode to disassemble the string into an array.

$path_arr=explode ("/", $path);

The core code is as follows:

if (isset ($_ server ["path_info"])) {
  $path=$_ server ["path_info"];
  $path=ltrim ($path, "/");
  $path_arr=explode ("/", $path);
}
if (isset ($path_arr [0])) {
  $key=$path_arr [0];
  unset ($path_arr [0]);
}
else {
  $key="";
}
if (isset ($path_arr [1])) {
  $parameters=array_values ​​($path_arr);
}
if (isset ($route [$key])) {
  $arr=explode ("@", $route [$key]);
  $controller=new $arr [0];
  $action=$arr [1];
  if (isset ($parameters)) {
    $controller->$action ($parameters);
  }
  else {
    $controller->$action ();
  }
}
else {
  require "error.html.php";
}

The unset function can destroy the key and value in the array, but it will not rebuild the index.So path_arr [0] is the controller class and method name to be called,path_arr [1] or path_arr [1..n] are passed as arguments to the method.

Redirects and error pages are the most common in web systems,Without the routing mechanism,You may have to endlessly repeat the redirect or error page display or jump code,With routing,It only takes one sentence to complete.

Reason 3:reduce the consumption of resources

mvc uses a controller to respond to requests. Each time a request comes,This controller should be initialized in a specified php file,Instead of doing initialization in separate php files,This can reduce the consumption of resources.

Do I have to use a controller?Option 1:No controller

We now add an item to the routing array,value is not a string,But an anonymous function (closure)

$route=[
  "" =>"index",  "blog" =>"[email protected]",  "blog/{id}/{name}" =>"[email protected]",  "f" =>function () {echo "hello";}
];

Here route [f] is an anonymous function,Not a method of a controller class,Therefore, we need to modify the routing code in the previous section:

if (isset ($route [$key])) {
  if ($route [$key] instanceof closure) {
    $route [$key] ();
  }
  else {
    $arr=explode ("@", $route [$key]);
    $controller=new $arr [0];
    $action=$arr [1];
    if (isset ($parameters)) {
      $controller->$action ($parameters);
    }
    else {
      $controller->$action ();
    }
  }
}
else {
  require "error.html.php";
}

Option 2:Using the controller

It is not elegant to require an html page every time.So we write a render function

function render ($path, array $args) {
  extract ($args);
  require ($path);
}

Continue from the previous blog,We know that each uri corresponds to a method,But we often encounter such problems:

<?php
class controller {
  public function __call ($method, $args) {
    echo "has not this function". $method;
  }
}
class indexcontroller extends controller {
  public function index () {
    echo __class__;
    for ($i=1;$i<= 20;++ $i) {
      $data [$i]="content";
    }
    render ("template.html.php", ["data" =>$data]);
  }
}
class blogcontroller extends controller {
  public function show () {
    echo __class__;
    for ($i=1;$i<= 10;++ $i) {
      $data [$i]="blog";
    }
    render ("template.html.php", ["data" =>$data]);
  }
}
?>

With or without controllerDepends on the complexity of your business.Personally recommend using a controller,But for business simple page jumps or checks,Can be written directly in an anonymous function.

What is written in the controller?

We may have written code like this:

class indexcontroller extends controller {
  public function index ($content) {
    return "&html;<head></head><body>". $content. "</body></html>";
  }
}

Writing the interface code in this way is very difficult to maintain.It is also the most disgusting expression of many developers (including me).Because this writing doesn't separate the interface from the business logic.So we need to use views.

<html>
  <head>
  </head>
  <body>
    <?php foreach ($data as $key =>$value) {?>
      <div>
        <?php echo $key. ":". $Value;?>
      </div>
    <?php}?>
  </body>
</html>

Every time a method of the controller is called,The render function will pass parameters as an associative array.To achieve a shallow separation of "business logic" and "performance",But this separation is not the best,Because front-end developers still need to face and even process PHP code, back-end developers also have the cost of communicating with front-end staff,So one verse later,Will talk about a better way to separate.

php
  • Previous Summary of task scheduling console usage in Laravel
  • Next Solve the problem of blank at the end when switching between plain text and cipher text with UITextField in iOS