1.前置操作 app\index\controller\Demo4
<?php
#前置操作,設置 beforeActionList屬性可以指定某個方法爲其他方法的前置操作
namespace app\index\controller;
use think\Controller;
class Demo4 extends Controller
{
protected $beforeActionList = [
'first', //first是所有方法(不包含前置操作)的前置操作
'second' => ['except'=>'hello'], //second是除了hello()以外所有方法的前置操作
'three' => ['only'=>'hello,data'],//three是隻有hello()和data()的前置操作
];
/**
* [1]數組鍵名爲需要調用的前置方法名
* [2]數組的值來確定前置方法使用的約束,
* 2.1 值爲空就是指當前方法是所有方法的前置操作
* 2.2 except屬性指定的方法不能使用當前方法爲前置操作
* 2.2 only 只有指定的方法使用當前前置操作
*/
protected function first()
{
echo 'first<br/>';
}
protected function second()
{
echo 'second<br/>';
}
protected function three()
{
echo 'three<br/>';
}
public function hello()
{
return 'hello';
}
/**http://localhost:8090/tpjiuzhu30/public/index.php/index/demo4/hello
* first
* three
* hello
*/
public function data()
{
return 'data';
}
/**
* http://localhost:8090/tpjiuzhu30/public/index.php/index/demo4/data
* first
* second
* three
* data
*/
}
2.空操作 app\index\controller\City
<?php
namespace app\index\controller;
/**
* 空操作是指系統在找不到指定的操作方法的時候,會定位到空操作(_empty)方法來執行,利用這個機制,我們可以實現錯誤頁面和一些URL的優化。
*/
class City
{
public function _empty($name)
{
//把所有城市的操作解析到city方法
return $this->showCity($name);
}
//注意 showCity方法 本身是 protected 方法
protected function showCity($name)
{
//和$name這個城市相關的處理
return '當前城市' . $name;
}
}
/**
* 接下來,我們就可以在瀏覽器裏面輸入
* http://serverName/index/city/beijing/
* http://serverName/index/city/shanghai/
* http://serverName/index/city/shenzhen/
* 由於City並沒有定義beijing、shanghai或者shenzhen操作方法,因此係統會定位到空操作方法_empty中去解析
* ,_empty方法的參數就是當前URL裏面的操作名,因此會看到依次輸出的結果是:
* 當前城市:beijing
* 當前城市:shanghai
* 當前城市:shenzhen
*/
3.空控制器 app\index\controller\Error
<?php
namespace app\index\controller;
use think\Request;
/**
* 空控制器的概念是指當系統找不到指定的控制器名稱的時候,系統會嘗試定位空控制器(Error),
* 利用這個機制我們可以用來定製錯誤頁面和進行URL的優化。
*/
class Error{
public function index(Request $request)
{
//根據當前控制器名來判斷要執行那個城市的操作
$cityName = $request->controller();
return $this->city($cityName);
}
//注意 city方法 本身是 protected 方法
protected function city($name)
{
//和$name這個城市相關的處理
return '當前城市' . $name;
}
}