六.空操作
空操作是指系統在找不到請求的操作方法時,會定位到空操作(_empty)方法來執行,利
用這個機制,我們可以實現錯誤頁面和一些 URL 的優化。
在 WeiBo/Home/Controller/UserController.class.php 中的代碼 為:
1 <?php 2 3 namespace Home\Controller; 4 use Think\Controller; 5 6 class UserController extends Controller { 7 public function index() { 8 echo "this is index "; 9 } 10 }
這時如果url為: http://localhost/demo39/user/index 則輸出為: this is index ,
但如果url為: http://localhost/demo39/user/test 則

這時為了不出現上圖,則添加函數 _empty()
在 WeiBo/Home/Controller/UserController.class.php 添加如下代碼:
1 public n function _empty($name) { 2 echo '找不到方法:'.$name; 3 }
這時當url為: http://localhost/demo39/user/test ,則輸出為:

七. 空控制器
所謂空控制器,就是請求不到指定控制器時,調用一個專門的空控制器。利用這個機制,
我們可以實現錯誤頁面和一些 URL 的優化。
這時在 WeiBo/Home/Controller/Controller 下新建 EmptyController.class.php ,與 IndexController.class.php 同級,
代碼為:
1 <?php 2 namespace Home\Controller; 3 use Think\Controller; 4 5 class EmptyController extends Controller { 6 public function index() { 7 echo "找不到控制器:".CONTROLLER_NAME; 8 } 9 }
這時url為: http://localhost/demo39/test ,輸出為: 找不到控制器:Test ,就不會出現出錯頁面了。
八.操作綁定到類
ThinkPHP 提供了把每個操作方法定位到一個類的功能,即每個把層次分的更加細膩。
在 WeiBo/Common/Conf/config.php 中進行配置:
1 //設置操作綁定到類 2 'ACTION_BIND_CLASS'=>
然后,在 Controller 目錄下建立 User 目錄,在 User 目錄建立 index.class.php,
再建立 test.class.php。
1 //index.class.php內代碼 2 namespace Home\Controller\User; 3 use Think\Controller; 4 class index extends Controller { 5 public function run() { 6 echo 'User模塊下的index類'; 7 } 8 }
1 //test.class.php內代碼 2 namespace Home\Controller\User; 3 use Think\Controller; 4 class test extends Controller { 5 public function run() { 6 echo 'User模塊下的test類'; 7 } 8 }
需要注意的是,在User目錄下的 class.php 文件如 index.class.php 中的 index 中的i不要大寫,否則會出錯(調試了半天才發現是大寫首字母I出的錯)
且 index.class.php 中的function必須是run() 函數。
這時在 index.class.php 中插入其它代碼如下:
1 public function abc() { 2 echo 'User模塊下的abc類'; 3 }
是不起作用的。
要對 index.class.php 中的run()函數增加其它功能的話可使用以下函數:
1 //前置后置方法 2 public function _before_run() { 3 echo 'before_'.ACTION_NAME; 4 } 5 public function _after_run() { 6 echo 'after_'.ACTION_NAME; 7 }
空方法,在User目錄里建立一個 _empty.class.php 與 index.class.php 同級
1 <?php 2 namespace Home\Controller\User; 3 use Think\Controller; 4 5 class _empty extends Controller{ 6 public function run() { 7 echo "找不到方法:".ACTION_NAME; 8 } 9 }
空控制器,可以創建一個目錄 _empty 與 User 目錄同級,然后建立 index.class.php
1 <?php 2 namespace Home\Controller\_empty; 3 use Think\Controller; 4 5 class _empty extends Controller{ 6 public function run() { 7 echo "找不到該控制器:".CONTROLLER_NAME; 8 } 9 }
文章列表
留言列表
