About ThinkPHP controller analysis

不言
Release: 2023-03-30 18:50:01
Original
1695 people have browsed it

Generally speaking, ThinkPHP's controller is a class, and the operation is a public method of the controller class. Let's talk about ThinkPHP's controller in detail

In the previous course, you may have some doubts about ThinkPHP's routing, but it doesn't matter. After studying this course, many things will suddenly become clear.

Controller file naming follows the method of IndexController.class.php

Controller definition

Before we start, we still need Clarify the definition of the controller:

<?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>";
  }

}
Copy after login

As you can see, the controller mentioned earlier in the routing chapter is defined like this:

Use the corresponding namespace, the default is namespace Home\Controller
Load Think\Controller
The new controller inherits from Controller (or subclass)
Use camel case naming method, pay attention to the capitalization of the first letter
Controller The public methods within can be regarded as an operation. For example, the read() and top() methods above can be regarded as operations. We have verified this in the routing chapter.

http://localhost:8999/index.php/Home/Index/top
means accessing the top() method, which will print out the top page on the page, and once again make it clear that Home represents Home Module

Sometimes you may encounter methods that conflict with the system's keywords. In this case, you can use the setting operation method suffix to solve the problem.

Pre- and post-operations

Pre- and post-operations refer to methods that are automatically called before and after executing an operation method, but only Valid for access controllers, such as adding pre- and post-methods to the top() method in IndexController:

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>";
  }
Copy after login

Access: http://localhost:8999 /index.php/Home/Index/top

You will see the printout:

before top page
top page
after top page
Copy after login

Use pre- and post-operation requirements Note the following two points:

If the current operation does not define an operation method, but directly renders the template file, then if the pre- and post-methods are defined, they will still take effect. The real template output may only be the current operation, and the pre- and post-operations generally do not have any output.

It should be noted that if exit or error output is used in some methods, the post-method may no longer be executed. For example, if the error method of the system Action is called in the current operation, the post-operation will not be executed, but the post-method execution of the success method will not be affected.

Can be used for form filtering and verification

Parameter binding

Parameter binding is to directly bind the variables in the URL address as parameters of the operation method, which can simplify the definition of the method and even routing. parse.

&#39;URL_PARAMS_BIND&#39;    => true
Copy after login

The parameter binding function is enabled by default. The principle is to bind the parameters in the URL (excluding module, controller and operation names) with the parameters in the operation method. .
There are two ways to bind parameters: binding according to variable name and binding according to variable order. The default is to bind according to variable name. For example, look at the following example:

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

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

Yes, this is the content involved in the previous routing. In the routing settings of the previous routing

'blogs/:id'     => array('Index/read' )
We mapped :id directly to the parameter $id of the read() method, so looking back now, the routing rules actually give you the function of customizing the URL. If we remove the above routing settings, our correct access method is:

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

The id in the above URL is the variable If you write the name as:

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

, then the access address is:

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

For the case of multiple parameter binding, just pass in the corresponding variable name and value, regardless of the order. For example, the following two will return the same result:

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

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

It should be noted that no matter what situation, when you visit

http://localhost:8999/index.php/Home /index/read/
will report an error:

Parameter error or undefined: id
A good way to solve this problem is to set default values ​​for bound parameters, such as:

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

In this way, accessing the above URL again will output:

read page with
0

tips : Setting default values ​​for binding parameters is a good way to avoid errors
In actual development, we will actually see URLs that do not display variable names, such as:

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

How to solve it? At this time, we can actually use the second type of parameter binding: binding in variable order. To use this parameter binding, you need to set it in the setting item first:

&#39;URL_PARAMS_BIND_TYPE&#39; => 1
Copy after login

一旦设置变量顺序绑定,这种情况下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。但我们可以自己设置,例如

&#39;URL_HTML_SUFFIX&#39;=>&#39;shtml&#39;
Copy after login

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

&#39;URL_HTML_SUFFIX&#39; => &#39;html|shtml|xml&#39;
Copy after login

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

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

&#39;URL_DENY_SUFFIX&#39; => &#39;pdf|ico|png|gif|jpg&#39;,
Copy after login

注: 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(&#39;Article/cate&#39;,array(&#39;cate_id&#39;=>1,&#39;status&#39;=>1))
U(&#39;Article/cate&#39;,&#39;cate_id=1&status=1&#39;)
U(&#39;Article/cate?cate_id=1&status=1&#39;)
Copy after login

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

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

U(&#39;Article/cate/cate_id/1/status/1&#39;);
Copy after login

生成路由地址

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

&#39;blogs/:id\d&#39;=>&#39;Index/read&#39;
Copy after login

那么可以使用

U(&#39;/blogs/1&#39;);
Copy after login

最终生成的URL地址是:

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

跳转和重定向

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

跳转

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

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

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

<?php
namespace Home\Controller;

use Think\Controller;

class UserController extends Controller {

  public function addUser()
  {
    echo &#39;add user done!&#39;;
  }
}
Copy after login

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

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

// redirect to /Article/index after 3 seconds when success
$this->success(&#39;done&#39;,&#39;/Home/Article/index&#39;,3);
// redirect to /Article/error after 5 seconds when failed
$this->error(&#39;failed&#39;,&#39;/Home/Article/error&#39;,5);
Copy after login

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

define(&#39;BIND_MODULE&#39;,&#39;Home&#39;);
Copy after login

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

&#39;TMPL_ACTION_ERROR&#39; => THINK_PATH . &#39;Tpl/dispatch_jump.tpl&#39;,
&#39;TMPL_ACTION_SUCCESS&#39; => THINK_PATH . &#39;Tpl/dispatch_jump.tpl&#39;,
Copy after login

你可以根据自己的需要来修改模版。

重定向

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(&#39;/Home/Article/show&#39;, array(&#39;id&#39; => 2), 3, &#39;Redirecting...&#39;);
  }
Copy after login

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

namespace Home\Controller;

use Think\Controller;

class ArticleController extends Controller {

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

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

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

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

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

$this->redirect(&#39;/New/category/cate_id/2&#39;, 5, &#39;页面跳转中...&#39;);
Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

关于thinkphp3.2嵌入百度编辑器ueditor的解析

thinkPHP5.0框架访问URL的方法

The above is the detailed content of About ThinkPHP controller analysis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template