上一篇(ThinkPHP學習之windows下安裝並運行Hello World)最後一步,我們修改了IndexAction.class.action.php中的IndexAction類中的,index()方法體,我們將其修改成了Hello word。當在瀏覽器中輸入http://localhost/Index/index.php時,原來頁面中的笑臉,變成了index方法體中我們定義的Hello word。
接下來,在"/Index/Lib/"目錄下,創建一個新的控制器,文件名爲ShowAction.class.php,在該文件中,仿照indexAction.class.php那樣寫入如下內容:
<span style="font-size:14px;"><?php
class ShowAction extends Action {
public function abc(){
echo 'This is ShowAction abc method!';
}
}</span>
然後在瀏覽器敲入:“http://localhost/TestPHP/index.php?m=Show&a=abc”,運行,瀏覽器將返回如下結果:
This is ShowAction abc method!
由上面兩個例子,我們可以猜到,控制器是如何被調用的,即通過m和a這兩個參數,其中m是控制器名稱,a爲方法名。那麼爲什麼調用Index控制器的index方法時,就不用傳入m和a參數呢?這是因爲,ThinkPHP內部默認採用Index控制器。
爲了方便理解,我們修改index.php文件,修改爲:
<span style="font-size:14px;"><?php
print_r($_GET);
$control = isset($_GET['m']) ? $_GET['m'] : 'Index';
$obj = new $control();
$action = isset($_GET['a']) ? $_GET['a'] : 'index';
$obj->$action();
class IndexAction {
function __construct(){
echo "我被實例化了";
}
function index(){
echo "This is Index index";
}
function handle(){
echo "This is Index handle";
}
}
die();
define('APP_NAME','Index'); //定義項目名稱
define('APP_PATH','./Index/');//定義項目路徑
include './ThinkPhP/ThinkPHP.php';//引入核心文件
?></span>
上面代碼很直觀的展示了ThinkPHP內部的運行原理,其通過m參數來調用控制器類,使用a參數來調用方法,而在沒有m和a參數時,默認調用Index控制器的index方法。