"Seven-day self-made PHP framework" first day: Routing and Controller

Source: Internet
Author: User

Why do we use routing? Cause 1: A more beautiful URI

Improvements in 1.URI

When we started to learn PHP, we must have written a URI such as blog.php?id=1, and get the parameters using get methods. Such a URI has two shortcomings, one is easy to be SQL injection attack, and the second is the maintenance of poor readability, we can compare the following two kinds of URIs which is more readable.

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

The above URI is the most commonly used in our beginner PHP.

Www.mysite.com/blog/1

This URI is currently the most popular URI, for example, a lot of books, movies, such as Web sites, have used such URIs, such URIs than index.php?a=1&b=2&c=3&d=4 .... to be more concise.

2. Implementation methods

Write a. htaccess file in the root directory of the Web project

Rewriteengine onrewriterule ^ ([a-za-z0-9/]*) $ index.php/$1

Rewrite the rule so that the string behind the domain name is passed directly to the index.php as a parameter, so that index.php becomes the center of your entire Web application, defining the "mapping of requests and responses".

Cause 2: serviceability of the single entry mechanism

1. Routing Arrays

A PHP beginner, just started to do the project, the project is doing a large scale, often this PHP page to another PHP page with a GET method to pass value, sometimes passed the value of more than one, time, your Web project, n PHP page like a complex spider web, making it difficult to maintain. Once modified, it will involve a lot of PHP files, the workload is very large.

The single entry mechanism of MVC solves the problem of maintenance, and routing is a set of mappings that allows you to have a URI corresponding to a method.

$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;

We enter in the browser: After WWW.MYSITE.COM/BLOG/1, the path variable is/BLOG/1. Use the LTrim function to remove the left slash, and then use explode to split the string into groups.

$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 destroys the key and value in the array, but does not rebuild the index, so path_arr[0] is the controller class and method name to invoke, Path_arr[1] or PATH_ARR[1..N] as the parameter of the incoming method.

Redirect and error page is the most common Web system, if you do not use the routing mechanism, you may want to endless repeated write redirection or error page display or jump code, with a route, only a sentence can be completed.

Cause 3: Reduce the consumption of resources

MVC uses a controller to respond to requests, and each time a request is made, the controller should be initialized in the specified PHP file instead of being initialized in separate PHP files, which can reduce the resource consumption.

Do you have to use a controller? Scenario 1: No controller

We now add an entry in 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 controller class method, so we have to change the previous section of the Routing code:

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 ';}
Scenario 2: Using the Controller

It's not elegant to require an HTML page every time, so let's write a render function

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

After a blog, we know that each URI corresponds to a method, but we often encounter such a problem:

<?php class Controller{public function __call ($method, $args) {echo ' have 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 no controller, it depends on the complexity of your business. Personal advice to use the controller, but for the business very simple page jump or check, you can directly write in an anonymous function.

What does it say in the controller?

We may have written this code:

Class Indexcontroller extends controller{public    function Index ($content) {        return ' 

This way of embedding the interface code is very difficult to maintain, but also a lot of developers (including me) the most offensive wording, because this writing is not good interface and business logic separation, so we need to use the view.

Each time a method of the controller is called, the render function passes the parameter in the form of an associative array, so that the "business logic" and "performance" are separated at a shallow level, but this separation is not the best because the front-end developers still have to face and even process the PHP code, Back-end developers also have the cost of communicating with front-end personnel, so a later section will talk about a better way to separate.

"Seven-day self-made PHP framework" first day: Routing and Controller

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.