search
HomeBackend DevelopmentPHP TutorialThinkPHP学习之CURD操作(一)

写在前面

这周开始学习ThinkPHP,将学习的日记记录下来。不仅仅学习怎么用TP,也要从源码上来学习TP框架。

日记每天都写,但不一定都放到网上。希望自己能够坚持下去。

闲话少说,既然是阅读源码,关于TP的建立,配置等一系列操作就不去说了,官方文档有佷详细的介绍。

要同学想要学习TP的可以点击 ThinkPHP3.2.3快速入门 学习,大家一起进步。

CURD操作

什么是CURD操作?实际上是对数据库增删改查的简称。包括了create、update、read、delete四个基本操作。在TP中对CURD操作的实现是add,save,select,update。

打开Think/Library/Model.class.php,可以在其中找到这四个操作。接下来就开始来查看源码,知道运行的流程,才能够更好的运用这四个操作。

CUED操作之add方法

add方法用于数据添加,是TP对create操作的实现。注意一点的是,TPModel中也有create方法,但并不是CURD操作的一种,而是对即将插入数据库的数据的处理方法。

参数分析

add方法有三个参数(不必须传递),如下

$data 默认值'' 需要进行插入数据库的数据$option 默认值array() 表达式参数 其中存储着 所有进行过的连贯操作$replace 默认值false 是否在插入数据库时进行replace操作

返回值可能是bool(false)或数据库受影响的行数或主键值。从返回值看出该操作是必须位于连贯操作的末尾,可以看成一连套组合技中的终结技。

流程分析

我对add方法的执行流程分成了四步

  • 首先,检测数据是否为空
  • 其次,进行数据处理与表达式分析
  • 以上都通过 进行数据插入 返回插入结果
  • 对返回的结果进行分析

步骤一假设进行用户注册操作,插入数据表User,使用add方法进行操作。user字段为:

主键 user_id昵称 user_name密码 password邮箱 email

前台POST数据:

array(    'user_name'     => 'xiamsahfw',    'password'      => 'adhe99211' ,    'confrim'       => 'adhe99211' ,    'email'         => '221131@qq.com',    'hid'           => 'register'              );

在UserController类中的操作:

$data = I('post.');$User = M('User');$User->create($data);$User->add();

在add操作中,并没有给add传递任何参数,但在$User->create($data)中传递了该值,在该操作中就会自动将数据添加到Model中的$this->data中,而add会自动引用该值。

同时create方法会将自动将传递的参数与数据表的字段进行对比,将不属于表中的字段删除。

步骤二之后,add方法就会调用_facade方法对$data进行数据处理,其实在这里是二次处理$data数据,因为在create方法以及对数据进行过处理。如果在UserController中并没有调用create方法,而是直接传递$data到add方法,那么_facade就会把'confrim' => 'adhe99211' ,'hid' => 'register'删除,变成:

array(     'user_name'     => 'xiamsahfw',     'password'      => 'adhe99211' ,     'email'         => '221131@qq.com'                );

为了可能的连贯操作,add会调用_parseOptions进行表达式分析。在表达式分析后即使没进行任何连贯操作,在返回的值也存在两个元素:

Array ([table] => user[model] => User)

table表示操作的数据表,model表示操作的模型名。

如果之前存在连贯操作,如where,group by等也会在该项显示。此外,传递连贯操作到add方法,也会和已经存在的操作进行合并。

步骤三以上其实都是数据插入的准备工作,准备工作完成就能够进行数据插入了。当然数据插入不属于Model的功能,在TP中需要调用Think\Driver.class.php中的insert方法。

insert方法接受三个参数

$data$option$replace

前两个参数是处理过的数据以及组合后的连贯操作表达式,第三个参数表示在插入数据库时,是否进行replace操作,默认为false。在这个方法中会将传递的数据与连贯操作表达式进行组合,形成正式的sql语句,并执行sql语句。最后返回执行结果。

步骤四虽然得到了返回结果,add并不是直接将结果返回,而是返回分析后的结论。insert返回的结果,可能有:

失败 => false成功 => 返回受影响的行数

但是实际进行中,我们可能会不仅想要得到一个插入成功的结论,而是想要得到插入后的主键值。在add方法中会对返回结果进行判断,从而返回受影响的行数(多条数据插入)或主键值(一条数据)或false。

题外话:在进行数据插入之前我注意到有这么一行代码。

if(false === $this->_before_insert($data,$options)) {    return false;}

这里TP没有做任何注释,寻找之后,发现是一个空方法,解释为 插入数据前的回调方法

// 插入数据前的回调方法protected function _before_insert(&$data,$options) {}

将这个方法打印出来,结果为NULL

var_dump($this->_before_insert($data,$options));  // NULL

百度一下也没找到想要的答案,我对TP的官方文档并没有看完,可能官方会有用法的介绍。这里很纠结,我猜测是在子类继承时,可以实现这个方法进行某些特殊操作(很大可能)。与之相同的还有_after_insert方法。

总结

写了一大串,也不知道写的是不是很清晰,但是我的确是对这个方法熟悉了很多。这个方法虽然可以不传递参数,但如果之前没进行create还是会出错的,虽然内部集成了数据处理,但不是很完善,比如对数据没能进行转义,也不能够对数据字段进行验证,需要我们自己进行调用其它方法等等。知道了add的运行原理,自然能够很好的运用它,同时对自己封装模型类时也有了很大启发。

今天就写到这儿,下一篇准备写CURD中的read,也就是TP中的select。

博主大三狗,正在努力学习中,文中有错漏之处难免,欢迎指正,欢迎批评。

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
PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment