fatfree-f3小型php架構(二)
我們的第一個例子不是太難懂吧,但是如果要做更多的功能與要求,我們就要在$f3 -> run()之前加一些別的路由:
$f3->route('GET /about', function() { echo 'Donations go to a local charity... us!'; });如果你不想把全域的命名弄得太亂,fatfree有不同的映射路由的方法去管理物件導向的類與方法:
class WebPage { function display() { echo 'I cannot object to an object'; }}$f3->route('GET /about','WebPage->display');
http的要求同樣也能路由到靜態類函數:
$f3->route('GET /login','Auth::login');
路由和符號:
作為fatfree這樣一門強大的特殊領域語言,可以指定單一的路由區控制不同的情況:
$f3->route('GET [email protected]', function($f3) { echo $f3->get('PARAMS.count').' bottles of beer on the wall.'; });[email protected],[email protected]rew/98([email protected]值為98)或者/brew/99這樣子,然後這個98就會賦值[email protected],調用funtion去輸出“98 bottles of beer on the wall”.
除了數字之外,[email protected],例如/brew/unbreakable然後就輸出“unbreakable bottles of beer on the wall”.
還有另外一招:
$f3->route('GET [email protected]', function($f3,$params) { echo $params['count'].' cars.'; });
還有一個方法,用“*”來代替任何不重要的資訊,例如:
$f3->route('GET /car/*', function() { echo 'We have enough cars.'; });就是無論輸入什麼在/car/#$#%#@$#@[email protected]
如果要改變方法去別的網頁,我們可以用這招:
$f3->route('GET|HEAD /go_google', function($f3) { $f3->reroute('http://www.google.com'); });
也就是說輸入 http://localhost/go_google就可以跳轉頁面了。(注意,這些都是在index.php中定義的,進入檔案夾後會自動搜index中的路由,會自動識別到底是路由還是檔案夾的,別擔心)
reroute方法就是跳轉頁面用的,而且前面同事用到了GET和HEAD要求,除此之外還有一個POST,這個大家可以瞭解一下他們的區別。
給路由命名:
當你定義一個路由的時候,你可以給路由命名。可以用代碼中路由的名字和模板來替代URL的類型。如果你想要這麼做就要在定義路由的地方順便定義了路由的名字,for example
$f3->route('GET @beer_list: /beer', 'Beer->list');
同時要注意,路由的名字必須用php的命名規則。這個例子就說明[email protected]??。
然後調用的時候就要用到命名專屬數組ALISASES,看一個調用的例子
href="[email protected]_list}}">view beer list>
( a href是超連結的意思,可以看看html的用法)
當然了這種用法還可以用來跳轉頁面,例如剛剛學的那個reroute函數:
$f3->reroute([email protected]_list'); // note the single quotes
這次就不是跳轉到google上了,而是跳轉到“/beer”的頁面上。
同時,我們常用的重載函數也適合這種情況,例子:
$f3->route('GET @beer_list: [email protected]', 'Beer->bycountry');$f3->route('GET @beer_list: [email protected][email protected]', 'Beer->byvillage');// a set of key-value pairs is passed as argument to named route$f3->reroute([email protected]_list(@country=Germany)');// if more than one token needed$f3->reroute([email protected]_list(@country=Germany,@village=Rhine)');
[email protected]_list這個變數重載了,當然調用的分別是bycountry和byvillage兩個不同的函數,然後根據這兩個方法的不同來分別給參數,[email protected][email protected],[email protected]?果給兩個,自然就是調用下面那個。
-
1樓modiziri昨天 10:19
-
恩恩