thinkphp空操作和設定檔實現簡化路由

來源:互聯網
上載者:User

1關於TP中空操作和路由問題

<?phpfunction test(){    $content="test demo @雲峰天下";    $pattern='/@(\S+)\s/';    $content=preg_replace($pattern,'<a href="'.__APP__.'/user/index/uname/\\1">\\1</a>');     return $content;   }

最近在做一個微博,有一塊是微博內容@使用者加連結,跳轉到使用者頁,剛開始感覺沒什麼難的,可以通過正則替換實現。

就像上面一樣,將使用者名稱使用get傳值帶到相應的控制器下面的方法下去。但是url確實太長,看了下視頻中的介紹,使用了

空操作和路由進行了處理。

<?phpfunction test(){    $content="test demo @雲峰天下";    $pattern='/@(\S+)\s/';    $content=preg_replace($pattern,'<a href="'.__APP__.'/user/\\1">@\\1</a>');     return $content;   }

將代碼進行修改後如上,修改後連結是這樣:<a href="localhost/weibo/user/雲峰天下">@雲峰天下</a>,但是user控制器下是沒有這個方法的?

最後看完視頻感覺tp挺強大的,是通過定義一個空操作和通過使用者名稱擷取使用者id,再通過配置路由從而實現簡化路由

/**     * 空操作     */    function _empty($name){        $this->_getUrl($name);    }    /**     * 處理使用者名稱空操作,獲得使用者ID,跳轉至使用者個人頁     */    private function _getUrl($name){        $where=array('username'=>$name);        $uid=M('userinfo')->where($where)->getField('uid');                    if(!$uid){            redirect(U('Index/index'));        }else{            redirect(U('/'.$uid));            //redirect(U('index',array('uid'=>$uid)));        }    }

在上面中由於是訪問user下的每個使用者名稱作為方法,會執行_empty()方法,該方法下調用私人方法_getUrl(),跳轉到localhost/weibo/index.php/4(使用者id號),由於該模組不存在,因此需要通過設定檔中的路由配置實現,如下

//URL路由配置    'URL_ROUTER_ON'=>true,   //開啟路由功能    'URL_ROUTE_RULES'=>array(   //定義路由規則        ':id\d'=>'User/index'    )

查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/webkf/PHP/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.