Bei der Verwendung von Website-Software habe ich festgestellt, dass die index.php im Stammverzeichnis mancher Software mehrere verschiedene Webseiten generieren kann, wie zum Beispiel:
localhost/index.php/blog; localhost/index.php/contact.
Wie wird diese Routing-Methode implementiert? Danke!
對于localhost/index.php
,訪問的文件地址是 localhost/index.php
沒錯(cuò),然后 /blog
,可以理解成參數(shù),
至于怎么獲取呢 ?查看 $_SERVER 的信息吧。
比如說,'/blog' 參數(shù)對應(yīng)的是 Blog 控制器的 index 方法,然后可以通過調(diào)用 (new Blog())->index() 實(shí)現(xiàn)相應(yīng)的邏輯。
在往下說,'/blog/add' 參數(shù),對應(yīng) Blog 控制器的 add 方法,然后可以通過調(diào)用 (new Blog())->index() 實(shí)現(xiàn)相應(yīng)的邏輯。
對于服務(wù)器來說,www.xxx.com/index.php/test只能識別到www.xxx.com/index.php,這個(gè)是在Nginx或者Apche里面配置的,例如下面一段配置:
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_intercept_errors off;
fastcgi_buffer_size 16k;
fastcgi_buffers 4 16k;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
}
至于后面的信息test,是PHP代碼自己去識別的,其實(shí)就是一個(gè)參數(shù),(至于PHP代碼怎么接收到這個(gè)參數(shù),你就得去看看Nginx或者Apache是怎么和PHP交互的了),當(dāng)這個(gè)參數(shù)"test"拿到以后,你就可以根據(jù)這個(gè)參數(shù)做你想做的事,不同的參數(shù),你就可以做不同的事,提供多樣的功能,這也是我對路由的理解。
后面的參數(shù)格式叫 PATH_INFO, apache默認(rèn)提示, nginx要自己正則匹配一下.
這個(gè)就和index.php?url=/path/to/xxx 一樣. 只是用一個(gè)參數(shù)來表示項(xiàng)目的路由的.