Home PHP Framework ThinkPHP The difference between thinkphp3 and thinkphp5

The difference between thinkphp3 and thinkphp5

Jun 19, 2019 pm 03:43 PM
thinkphp5 the difference

The difference between thinkphp3 and thinkphp5

What is the difference between thinkphp3 and thinkphp5? Let me introduce to you the differences between the two:

1. The usage differences between thinkphp3.2 and thinkphp51. The past single-letter functions have been completely replaced, as follows:

S=>cache,C=>config,M/D=>model,U=>url,I=>input,E=>exception,L=>lang,A=>controller,R=>action
Copy after login

2. Template rendering:

$this->display() => return view()/return $this->fetch();
Copy after login

3. Calling the own model in the model:

$this => Db::table($this->table)
Copy after login

4. Naming when creating a new controller and model:

① Remove the suffix controller from the controller: UserController => User

② Remove the suffix model from the model: UserModel => User

5. URL access:

If the controller name uses camel case, you need to link each letter with an underscore before accessing.

eg: The controller name is AddUser, and access is done using add_user

6. In TP5, it supports configuring secondary parameters (i.e. two-dimensional array). In the configuration file, the secondary Configuration parameter reading:

①Config::get('user.type');

②config('user.type');

7. The template supports three Operations of meta-operators:

{$info.status ? $info.msg : $info.error}还支持这种写法:{$varname.aa ?? 'xxx'}或{$varname.aa ?: 'xxx'}
Copy after login

Related recommendations: "

php video tutorial

"8. TP5 built-in tags:

In the system's built-in tags , volist, switch, if, elseif, else, foreach, compare (including all comparison tags), (not) present, (not) empty, (not) defined, etc.

9. TP5 data verification:

$validate = new Validate(['name' => 'require|max:25','email' => 'email']);
$data = ['name' => 'thinkphp','email' => 'thinkphp@qq.com'];
if(!validate->check($data)){
debug::dump($validate->getError());
}
Copy after login

Note: Use the helper function to instantiate the validator - $validate = validate('User');

10. TP5 implements built-in paging, use the following:

Query user data with status 1, and display 10 pieces of data per page

$list = model('User')->where('status',1)->paginate(10);
$page = $this->render();
$this->assign('_list',$list);
$this->assign('_page',$page);
return $this->fetch();
Copy after login

The paging output code in the template file is as follows:

<div>{$_page}</div>
Copy after login

Second, thinkphp3.2 and thinkphp5 database operations for comparison

Add data

thinkhp3.2

//添加单条数据$User = M(&#39;User&#39;);
$data[&#39;name&#39;] = &#39;ThinkPHP&#39;;
$data[&#39;email&#39;] = &#39;ThinkPHP@gmail.com&#39;;
$User->create($data);
$User->add($data);//添加多条数据$dataList[] = array(&#39;name&#39;=>&#39;thinkphp&#39;,&#39;email&#39;=>&#39;thinkphp@gamil.com&#39;);
$dataList[] = array(&#39;name&#39;=>&#39;onethink&#39;,&#39;email&#39;=>&#39;onethink@gamil.com&#39;)
$User->addAll($dataList);
Copy after login

thinkphp5

//添加单条数据$data = [&#39;foo&#39; => &#39;bar&#39;, &#39;bar&#39; => &#39;foo&#39;];
Db::table(&#39;think_user&#39;)->insert($data);//添加多条数据$data = [
    [&#39;foo&#39; => &#39;bar&#39;, &#39;bar&#39; => &#39;foo&#39;],
    [&#39;foo&#39; => &#39;bar1&#39;, &#39;bar&#39; => &#39;foo1&#39;],
    [&#39;foo&#39; => &#39;bar2&#39;, &#39;bar&#39; => &#39;foo2&#39;]
];
Db::name(&#39;user&#39;)->insertAll($data);
Copy after login

Modify Data

thinkhp3.2

$User = M("User"); // 实例化User对象// 要修改的数据对象属性赋值
$data[&#39;name&#39;] = &#39;ThinkPHP&#39;;$data[&#39;email&#39;] = &#39;ThinkPHP@gmail.com&#39;;
$User->where(&#39;id=5&#39;)->save($data); // 根据条件更新记录
where(&#39;id=5&#39;)->setField(&#39;name&#39;,&#39;ThinkPHP&#39;);
$data = array(&#39;name&#39;=>&#39;ThinkPHP&#39;,&#39;email&#39;=>&#39;ThinkPHP@gmail.com&#39;);// 更改用户的name值
$User-> where(&#39;id=5&#39;)->setField($data);更改用户的name和email的值
$User->where(&#39;id=5&#39;)->setDec(&#39;score&#39;,5); // 用户的积分减5
$User->where(&#39;id=5&#39;)->setInc(&#39;score&#39;,3); // 用户的积分加3
Copy after login

thinkhp5

Db::table(&#39;think_user&#39;)->update([&#39;name&#39; => &#39;thinkphp&#39;,&#39;id&#39;=>1]);//更新数据表中的数据
Db::table(&#39;think_user&#39;) ->where(&#39;id&#39;,1) ->setField(&#39;name&#39;, &#39;thinkphp&#39;);//更新某个字段的值
Db::table(&#39;think_user&#39;)->where(&#39;id&#39;, 1)->setInc(&#39;score&#39;,5);// score 字段加 5
Db::table(&#39;think_user&#39;)->where(&#39;id&#39;, 1)->setDec(&#39;score&#39;, 5);// score 字段减 5
Db::table(&#39;think_user&#39;)->where(&#39;id&#39;, 1)->setInc(&#39;score&#39;, 1, 10);//支持延时更新
Copy after login

Delete data

thinkhp3.2

$User->delete(&#39;1,2,5&#39;); // 删除主键为1,2和5的用户数据
$User->where(&#39;status=0&#39;)->delete(); // 删除所有状态为0的用户数据
Copy after login

thinkphp5

// 根据主键删除Db::table(&#39;think_user&#39;)->delete(1);
Db::table(&#39;think_user&#39;)->delete([1,2,3]);// 条件删除    
Db::table(&#39;think_user&#39;)->where(&#39;id&#39;,1)->delete();
Db::table(&#39;think_user&#39;)->where(&#39;id&#39;,&#39;<&#39;,10)->delete();
Copy after login

Third, comparison between thinkphp5 and thinkphp3. Developers of the .X version can get familiar with and get started with this new version faster. At the same time, it is also strongly recommended that developers abandon their old thinking patterns, because 5.0 is a brand new subversive and reconstructed version. Old ideas of 3. We apologize for the incorrect guidance. In version 5.0, the method similar to /id/1, which can obtain 'id' through 'get', is officially abolished. Strictly speaking, such a URL does not belong to $_GET. Now it can be obtained through 'param' Obtain.

Model changes

The new version of the model query returns the default 'object', and the system adds the 'toArray' method by default. Many developers use 'all' or 'select' 'Try to use 'toArray' to convert to an array. I hope developers can understand the concept of 'object', try to use 'object' to use data, or use the 'db' method to operate the database, and also remind you of this part' For developers who abuse 'toArray', the result of 'all' or 'select' is an array collection of objects, which cannot be converted using 'toArray'.

New version changes

Naming convention

Directory and file names use 'lowercase underscore', And start with a lowercase letter; class libraries and function files are uniformly suffixed with .php; class file names are defined in namespaces, and the path of the namespace is consistent with the path of the class library file (including upper and lower case); class names and class files The names should be consistent, and uniformly use camel case naming (the first letter is capitalized)

FunctionThe system no longer relies on any functions, but only provides assistants for commonly used operation encapsulation Function; single-letter functions are obsolete, and the system loads helper functions by default.

Routing

5.0 URL access no longer supports ordinary URL mode, and routing does not support regular routing definitions. Instead, all are changed to rule routing with variable rules (regular definition), the specific details will not be repeated here.

Controller

The namespace of the controller has been adjusted, and there is no need to inherit any controller class.

The namespace of the application class library is unified as app (modifiable) instead of module name; the class name of the controller does not have the Controller suffix by default. You can configure the controller_suffix parameter to enable the controller class suffix; the controller operation method Use the return method to return data instead of direct output; abolish the original pre- and post-operation methods;

Version comparison

3.2 version controller writing method

<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller 
{    public function hello()
    {        echo &#39;hello,thinkphp!&#39;;
    }
}
Copy after login
5.0 version controller writing method

namespace app\index\controller;
class Index
{    public function index()
    {        return &#39;hello,thinkphp!&#39;;
    }
}
Copy after login

3.2 version controller naming

IndexController.class.php
Copy after login

5.0 version controller naming

Index.php
Copy after login

Correct output template in the controller

5.0在控制器中输出模板,使用方法如下:

如果你继承think\Controller的话,可以使用:

return $this->fetch(&#39;index/hello&#39;);
Copy after login

如果你的控制器没有继承 think\Controller的话,使用:

return view(&#39;index/hello&#39;);
Copy after login

模型

如果非要对比与旧版本的改进,模型被分为数据库、模型、验证器三部分,分别对应M方法、模型、自动验证,同时均有所加强,下面做简单介绍。

数据库

5.0的数据库查询功能增强,原先需要通过模型才能使用的链式查询可以直接通过Db类调用,原来的M函数调用可以改用db函数,例如:
3.2版本

M(&#39;User&#39;)->where([&#39;name&#39;=>&#39;thinkphp&#39;])->find();
Copy after login

5.0版本

db(&#39;User&#39;)->where(&#39;name&#39;,&#39;thinkphp&#39;)->find();
Copy after login

模型

新版的模型查询增加了静态方法,例如:

User::get(1); 
User::all();
User::where(&#39;id&#39;,&#39;>&#39;,10)->find();
Copy after login

自动验证

对比旧的版本,可以理解为之前的自动验证且不同于之前的验证;
ThinkPHP5.0验证使用独立的\think\Validate类或者验证器进行验证,不仅适用于模型,在控制器也可直接调用。

配置文件

新版对配置很多的配置参数或者配置层次都和之前不同了,建议大家要么看看代码,要么仔细通读下官方的开发手册,不要因为配置的问题浪费自己一整天的时间。

异常

5.0对错误零容忍,默认情况下会对任何级别的错误抛出异常,并且重新设计了异常页面,展示了详尽的错误信息,便于调试。

系统常量的废弃

5.0版本相对于之前版本对系统变化进行了大量的废弃,用户如果有相关需求可以自行定义
下面是废除常量

REQUEST_METHOD IS_GET IS_POST IS_PUT IS_DELETE IS_AJAX __EXT__ COMMON_MODULE MODULE_NAME CONTROLLER_NAME 
ACTION_NAME APP_NAMESPACE APP_DEBUG MODULE_PATH等
Copy after login

部分常量可以在Request里面进行获取

助手函数

5.0助手函数和3.2版本的单字母函数对比如下:

The difference between thinkphp3 and thinkphp5

The above is the detailed content of The difference between thinkphp3 and thinkphp5. For more information, please follow other related articles on the PHP Chinese website!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the basic requirements for c language functions What are the basic requirements for c language functions Apr 03, 2025 pm 10:06 PM

C language functions are the basis for code modularization and program building. They consist of declarations (function headers) and definitions (function bodies). C language uses values ​​to pass parameters by default, but external variables can also be modified using address pass. Functions can have or have no return value, and the return value type must be consistent with the declaration. Function naming should be clear and easy to understand, using camel or underscore nomenclature. Follow the single responsibility principle and keep the function simplicity to improve maintainability and readability.

How to set password protection for export PDF on PS How to set password protection for export PDF on PS Apr 06, 2025 pm 04:45 PM

Export password-protected PDF in Photoshop: Open the image file. Click "File"&gt; "Export"&gt; "Export as PDF". Set the "Security" option and enter the same password twice. Click "Export" to generate a PDF file.

The difference between H5 and mini-programs and APPs The difference between H5 and mini-programs and APPs Apr 06, 2025 am 10:42 AM

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

Concept of c language function Concept of c language function Apr 03, 2025 pm 10:09 PM

C language functions are reusable code blocks. They receive input, perform operations, and return results, which modularly improves reusability and reduces complexity. The internal mechanism of the function includes parameter passing, function execution, and return values. The entire process involves optimization such as function inline. A good function is written following the principle of single responsibility, small number of parameters, naming specifications, and error handling. Pointers combined with functions can achieve more powerful functions, such as modifying external variable values. Function pointers pass functions as parameters or store addresses, and are used to implement dynamic calls to functions. Understanding function features and techniques is the key to writing efficient, maintainable, and easy to understand C programs.

Why do you need to call Vue.use(VueRouter) in the index.js file under the router folder? Why do you need to call Vue.use(VueRouter) in the index.js file under the router folder? Apr 05, 2025 pm 01:03 PM

The necessity of registering VueRouter in the index.js file under the router folder When developing Vue applications, you often encounter problems with routing configuration. Special...

What are the differences and connections between c and c#? What are the differences and connections between c and c#? Apr 03, 2025 pm 10:36 PM

Although C and C# have similarities, they are completely different: C is a process-oriented, manual memory management, and platform-dependent language used for system programming; C# is an object-oriented, garbage collection, and platform-independent language used for desktop, web application and game development.

How to use XPath to search from a specified DOM node in JavaScript? How to use XPath to search from a specified DOM node in JavaScript? Apr 04, 2025 pm 11:15 PM

Detailed explanation of XPath search method under DOM nodes In JavaScript, we often need to find specific nodes from the DOM tree based on XPath expressions. If you need to...

What are the different ways of promoting H5 and mini programs? What are the different ways of promoting H5 and mini programs? Apr 06, 2025 am 11:03 AM

There are differences in the promotion methods of H5 and mini programs: platform dependence: H5 depends on the browser, and mini programs rely on specific platforms (such as WeChat). User experience: The H5 experience is poor, and the mini program provides a smooth experience similar to native applications. Communication method: H5 is spread through links, and mini programs are shared or searched through the platform. H5 promotion methods: social sharing, email marketing, QR code, SEO, paid advertising. Mini program promotion methods: platform promotion, social sharing, offline promotion, ASO, cooperation with other platforms.

See all articles