search
HomeBackend DevelopmentPHP TutorialThinkPHP控制器详解_php技巧

在上一课程中,你可能会对ThinkPHP的路由会有一丝丝疑惑,不过没关系,学完本课程,很多事都会豁然开朗。

控制器文件命名遵守IndexController.class.php的方式

控制器的定义

在开始之前,我们还是需要明确一下控制器的定义:

<&#63;php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {

  public function read($id){
    echo "read page with </br>" .$id;
  }

  public function top(){
    echo "top page </br>";
  }

}

如所见,前面在路由篇提到的控制器就是这么定义的:

使用相应的命名空间,默认是namespace Home\Controller
加载Think\Controller
新建控制器继承于Controller(或子类)
采用驼峰命名法,注意首字母大写
控制器内的公共方法可以看作一个操作,比如上面的read()和top()方法就可以看作操作,我们在路由篇的时候都验证过了。

http://localhost:8999/index.php/Home/Index/top
就是访问到top()方法,会在页面上打印出top page ,再次明确Home代表的是Home模块

有时候可能会遇到有和系统的关键字冲突的方法,这时候就可以使用设置操作方法后缀来解决了,具体请看官方文档:
http://document.thinkphp.cn/manual_3_2.html#define_controller

前置和后置操作

前置和后置操作指的是在执行某个操作方法之前和之后会自动调用的方法,不过仅对访问控制器有效,如在IndexController中为top()方法添加前置后置方法:

public function _before_top(){
    echo "before top page </br>";
  }
  public function top(){
    echo "top page </br>";
  }
  public function _after_top(){
    echo "after top page </br>";
  }

访问:http://localhost:8999/index.php/Home/Index/top

就会看到打印出:

before top page
top page
after top page

使用前置和后置操作要注意如下两点:

如果当前的操作并没有定义操作方法,而是直接渲染模板文件,那么如果定义了前置和后置方法的话,依然会生效。真正有模板输出的可能仅仅是当前的操作,前置和后置操作一般情况是没有任何输出的。

需要注意的是,在有些方法里面使用了exit或者错误输出之类的话 有可能不会再执行后置方法了。例如,如果在当前操作里面调用了系统Action的error方法,那么将不会再执行后置操作,但是不影响success方法的后置方法执行

可以用于表单的过滤和验证

参数绑定

参数绑定是通过直接绑定URL地址中的变量作为操作方法的参数,可以简化方法的定义甚至路由的解析。

'URL_PARAMS_BIND'    => true


参数绑定功能默认是开启的,其原理是把URL中的参数(不包括模块、控制器和操作名)和操作方法中的参数进行绑定。
参数绑定有两种方式:按照变量名绑定和按照变量顺序绑定,默认使用的是按照变量名绑定,比如看下面的例子:

 public function read($id){
    echo "read page with </br>".$id;
  }

 public function archive($year, $month){
    echo "$year </br>".$month;
  }

对,这个就是上一篇路由所涉及的内容,在之前路由的路由设置处

'blogs/:id'               => array('Index/read')
我们将:id直接映射给read()方法的参数$id,所以现在回头再看,其实路由规则就是给了你一个自定义URL的功能。如果去掉上面的路由设置,我们正确的访问方式是:

http://localhost:8999/Home/index/read/id/3

上面的URl中id就是变量名,如果你写成:

 public function read($title){
    echo "read page with </br>".$title;
  }



那么访问地址就是:

http://localhost:8999/index.php/Home/index/read/title/3

对于多个参数绑定的情况,只要将相应的变量名和值传进来就可以了,不在乎顺序,比如下面两个会返回相同的结果:

http://localhost:8999/index.php/Home/index/archive/year/2012/month/12

http://localhost:8999/index.php/Home/index/archive/month/12/year/2012

需要注意的是,不管那种情况之下,当你访问

http://localhost:8999/index.php/Home/index/read/
是会报错的:

参数错误或者未定义:id
解决的一个好方法就是,给绑定的参数设置默认值,比如:

 public function read($id=0){
    echo "read page with </br>".$id;
  }

这样再次访问上面的URL,就会输出:

read page with
0

tips:给绑定参数设置默认值是一个避免报错的好办法
在实际的开发中,我们其实会见到没有显示变量名这样的URL,如:

http://localhost:8999/index.php/Home/index/read/3

怎么解决呢?这个时候,我们其实就可以用到第二种参数绑定:按照变量顺序绑定。要使用这种参数绑定,需要先在设置项中设置:

'URL_PARAMS_BIND_TYPE' => 1

一旦设置变量顺序绑定,这种情况下URL地址中的参数顺序非常重要,不能随意调整。这种情况下操作方法的定义不需要改变,只是访问的URL变了而已,现在用上面的方式访问就可以正确访问了。

如果在变量顺序绑定的情况下,我们访问:

http://localhost:8999/index.php/Home/index/archive/2012/12

http://localhost:8999/index.php/Home/index/archive/12/2012

这两个结果显然是不一样,后者并不是我们想要的。所以这种情况需要严格遵守顺序来传值。

伪静态

URL伪静态通常是为了满足更好的SEO效果,ThinkPHP支持伪静态URL设置,可以通过设置URL_HTML_SUFFIX参数随意在URL的最后增加你想要的静态后缀,而不会影响当前操作的正常执行,默认情况下,伪静态的设置为html。但我们可以自己设置,例如

'URL_HTML_SUFFIX'=>'shtml'

如果希望支持多个伪静态后缀,可以直接设置如下:

'URL_HTML_SUFFIX' => 'html|shtml|xml'

如果此项设置留空则表示可以支持所有的静态后缀。

也可以设置禁止访问的URL后缀通过URL_DENY_SUFFIX来设置,例如:

'URL_DENY_SUFFIX' => 'pdf|ico|png|gif|jpg',
注: URL_DENY_SUFFIX的优先级比URL_HTML_SUFFIX要高。

URL生成

为了配合所使用的URL模式,我们需要能够动态的根据当前的URL设置生成对应的URL地址,为此,ThinkPHP内置提供了U方法,用于URL的动态生成,可以确保项目在移植过程中不受环境的影响。

定义规则

U方法的定义规则如下(方括号内参数根据实际应用决定):
U('地址表达式',['参数'],['伪静态后缀'],['显示域名'])

地址表达式

地址表达式的格式定义如下:

[模块/控制器/操作#锚点@域名]?参数1=值1&参数2=值2...
如果不定义模块的话 就表示当前模块名称,下面是一些简单的例子:

U('User/add') // 生成User控制器的add操作的URL地址
U('Article/read?id=1') // 生成Article控制器的read操作 并且id为1的URL地址
U('Admin/User/select') // 生成Admin模块的User控制器的select操作的URL地址

参数

U方法的第二个参数支持数组和字符串两种定义方式,如果只是字符串方式的参数可以在第一个参数中定义,例如:

U('Article/cate',array('cate_id'=>1,'status'=>1))
U('Article/cate','cate_id=1&status=1')
U('Article/cate&#63;cate_id=1&status=1')


三种方式是等效的,都是生成Article控制器的cate()操作 并且cate_id为1 status为1的URL地址

但是不允许使用下面的定义方式来传参数:

U('Article/cate/cate_id/1/status/1');

生成路由地址

U方法还可以支持路由,如果我们定义了一个路由规则为:

'blogs/:id\d'=>'Index/read'

那么可以使用

U('/blogs/1');

最终生成的URL地址是:

http://localhost:8999/index.php/Home/blogs/1

跳转和重定向

这应该是在开发中最常用的功能之一。在应用开发中,经常会遇到一些带有提示信息的跳转页面,例如操作成功或者操作错误页面,并且自动跳转到另外一个目标页面。系统的\Think\Controller类内置了两个跳转方法success()和error(),用于页面跳转提示。

跳转

使用方法很简单,比如我们在Index控制器下新建一个方法user(),写上下面的内容:

public function user()
  {
    $User = M('User');
    $data['username'] = 'Think';
    $data['email'] = 'Think@gmail.com';
    $result = $User->add($data);
    if($result){
      $this->success('success', '/Home/User/addUser');
    } else {
      $this->error('failed');
    }
  }

M('User')表示实例化一个User对象,add()方法是向数据库添加一条纪录。然后我们需要新建一个UserController,在里面写上addUser()方法

<&#63;php
namespace Home\Controller;

use Think\Controller;

class UserController extends Controller {

  public function addUser()
  {
    echo 'add user done!';
  }
}

然后在浏览器中访问http://localhost:8999/Home/Index/user,就可以看到add user done!了,下面详细来说说这两个重定向方法。

success()和error()方法的第一个参数表示提示信息,第二个参数表示跳转地址,第三个参数是跳转时间(单位为秒),例如:

// redirect to /Article/index after 3 seconds when success
$this->success('done','/Home/Article/index',3);
// redirect to /Article/error after 5 seconds when failed
$this->error('failed','/Home/Article/error',5);

如果不设置跳转时间,默认的等待时间success()方法是1秒,error()方法是3秒。看到上面的两个跳转地址前面都带上了/Home,如果你想简写为/Article/index,你需要在ThinkPHP的入口文件(项目目录下的index.php)中加上下面一行:

define('BIND_MODULE','Home');

而且这两个方法都有对应的模板,默认的设置是两个方法对应的模板都是:

'TMPL_ACTION_ERROR' => THINK_PATH . 'Tpl/dispatch_jump.tpl',

'TMPL_ACTION_SUCCESS' => THINK_PATH . 'Tpl/dispatch_jump.tpl',
你可以根据自己的需要来修改模版。

重定向

Controller类的redirect()方法可以实现页面的重定向功能。
redirect()方法的参数用法和U函数的用法一致(参考上一部分URL生成部分),例如:

$this->redirect('/Home/Article/show', array('id' => 2), 3, 'Redirecting...');
上面的用法是停留3秒后跳转到Article控制器的show()操作,并且显示页面跳转中字样Redirecting...,重定向后会改变当前的URL地址。

为了成功进行测试,我们在IndexController下添加redirectToArticle()方法并写上上面那行代码:

public function redirectToArticle()
  {
    $this->redirect('/Home/Article/show', array('id' => 2), 3, 'Redirecting...');
  }

然后我们创建一个ArticleController,并且为他添加show()方法:

namespace Home\Controller;

use Think\Controller;

class ArticleController extends Controller {

  public function show($id)
  {
    echo 'This is an Article Page';
    // $id 变量我们后续会用到,现在只是演示跳转
  }
}

然后在浏览器访问:http://localhost:8999/Home/Index/redirectToArticle,等待三秒,你就可以看到跳转之后的页面了。

如果你仅仅是想重定向要一个指定的URL地址,而不是到某个模块的操作方法,可以直接使用redirect()函数重定向,例如

$this->redirect('/Home/Article/show/id/3', 'Redirecting...',3);

注:控制器的redirect()方法和redirect()函数的区别在于前者是用URL规则定义跳转地址,后者是一个纯粹的URL地址
注:好像官方文档是这样写的

$this->redirect('/New/category/cate_id/2', 5, '页面跳转中...');

以上所述就是本文的全部内容了,希望大家能够喜欢。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How can you prevent session fixation attacks?How can you prevent session fixation attacks?Apr 28, 2025 am 12:25 AM

Effective methods to prevent session fixed attacks include: 1. Regenerate the session ID after the user logs in; 2. Use a secure session ID generation algorithm; 3. Implement the session timeout mechanism; 4. Encrypt session data using HTTPS. These measures can ensure that the application is indestructible when facing session fixed attacks.

How do you implement sessionless authentication?How do you implement sessionless authentication?Apr 28, 2025 am 12:24 AM

Implementing session-free authentication can be achieved by using JSONWebTokens (JWT), a token-based authentication system where all necessary information is stored in the token without server-side session storage. 1) Use JWT to generate and verify tokens, 2) Ensure that HTTPS is used to prevent tokens from being intercepted, 3) Securely store tokens on the client side, 4) Verify tokens on the server side to prevent tampering, 5) Implement token revocation mechanisms, such as using short-term access tokens and long-term refresh tokens.

What are some common security risks associated with PHP sessions?What are some common security risks associated with PHP sessions?Apr 28, 2025 am 12:24 AM

The security risks of PHP sessions mainly include session hijacking, session fixation, session prediction and session poisoning. 1. Session hijacking can be prevented by using HTTPS and protecting cookies. 2. Session fixation can be avoided by regenerating the session ID before the user logs in. 3. Session prediction needs to ensure the randomness and unpredictability of session IDs. 4. Session poisoning can be prevented by verifying and filtering session data.

How do you destroy a PHP session?How do you destroy a PHP session?Apr 28, 2025 am 12:16 AM

To destroy a PHP session, you need to start the session first, then clear the data and destroy the session file. 1. Use session_start() to start the session. 2. Use session_unset() to clear the session data. 3. Finally, use session_destroy() to destroy the session file to ensure data security and resource release.

How can you change the default session save path in PHP?How can you change the default session save path in PHP?Apr 28, 2025 am 12:12 AM

How to change the default session saving path of PHP? It can be achieved through the following steps: use session_save_path('/var/www/sessions');session_start(); in PHP scripts to set the session saving path. Set session.save_path="/var/www/sessions" in the php.ini file to change the session saving path globally. Use Memcached or Redis to store session data, such as ini_set('session.save_handler','memcached'); ini_set(

How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor