ThinkPHP学习笔记(八)一个用户增删改查的小例子
主要是action文件的方法实现:
conf文件
<?php $selfConfig = array( //更换模式最好删除一些~app.php和~runtime.php //'配置项'=>'配置值' //因为开启URL重新不论是被重写的还是没被重写的,都可以通过原有路径访问 //如果想开启rewrite模式,需要做如下操作 //1.query服务器已经开启了Apache的rewrite模块 // LoadModule rewrite_module modules/mod_rewrite.so //2.在与主入口文件,统计目录下,新建一个.htaccess(vi:save .htaccess;记事本:".htaccess") //如果选用模式2(rewrite)会加大服务器的消耗 'URL_MODEL'=>1, 'URL_PATNINFO_MODEL'=>2, //pathinfo包含两类 //1普通模式:加上m和a:顺序关系可以发生变化 //http://localhost/MyThinkPHP/admin.php/m/index/a/index //传值 //http://localhost/MyThinkPHP/admin.php/m/index/a/index/username/zhangsan/password/password //2智能识别模块操作(默认模式就是智能识别) //http://localhost/MyThinkPHP/admin.php/index/index //传值 //http://localhost/MyThinkPHP/admin.php/index/index/username/zhangsan/password/password //修改URL分隔符 //'URL_PATHINFO_DEPR'=>'-', //修改模板左右定界符 'TMPL_L_DELIM'=>'<!--{', 'TMPL_R_DELIM'=>'}-->', //********************************非常华丽的分割线************************************** //开启调试模式 //1.模拟linux系统来识别大小写 //2.方法名的大小写与模板文件大小写有关 //注意:在分帧页面中,不能有body,但是app_dubug的信息是属于body体中的内容 'APP_DEBUG'=>true, //可以自定义页面的Trace信息 //配置文件路径的Trace信息配置在Thinkphp/Tpl下的pageTrace.tpl.php //自定义方式: //'TMPL_TRACE_FILE'=>APP_PATH.'/Public/trace.php', //或者自定义个trace.php页面放入当前的Conf文件夹中 //默认调试文件的位置: //ThinkPHP/Common/debug.php //不缓存数据库字段;如果开启,再修改可以将Runtim/Data下面的文件进行删除 //'DB_FIELDS_CACHE'=> false, //可以自定义的debug.php放入当前的Conf文件夹中 //先将APP_DEBUG设置为false然后在加入下面参数 //'APP_DEBUG'=>false, //显示运行次此页面需要的时间 //'SHOW_RUN_TIME'=>true, //显示详细的运行时间(基于SHOW_RUN_TIME) //'SHOW_ADV_TIME'=>true, //显示数据库的操作次数(基于SHOW_RUN_TIME) //'SHOW_DB_TIMES'=>true, //显示缓存的操作次数(基于SHOW_RUN_TIME) //'SHOW_CACHE_TIMES'=>true, //显示内存的开销(基于SHOW_RUN_TIME) //'SHOW_USE_MEM'=>true, //设置模板 //'DEFAULT_THEME'=>'default', //日志处理log类:lib/Think/Core/log.class.php //开启日志 //'LOG_RECORD'=>true, //日志处理log类:lib/Think/Core/log.class.php中有处理级别,可以选择性的加入 //'LOG_RECORD_LEVEL'=>array('EMERG','ALERT'), //由于数据库的链接需要多个项目来使用可以在一个页面中定义个公共的配置项,返回一个array数组 //连接数据库设置 //'DB_TYPE'=>'mysql', //'DB_HOST'=>'localhost', //'DB_NAME'=>'hibernate', //'DB_USER'=>'root', //'DB_PWD'=>'root', ////如果未修改可以不用填写 //'DB_POST'=>'3306', //'DB_PREFIX'=>'tb_', //令牌相关操作 //'TOKEN_ON'=>true, //'TOKEN_NAME'=>'__hash__', //'TOKEN_TYPE'=>'md5', ); $databaseConfig = include './database.php'; //连接返回之后并不好用,只能直接返回自定义的配置信息,可能是我的配置有问题,先留下这个问题 return array_merge($selfConfig,$databaseConfig); //return $selfConfig; ?>
外部引入的数据库链接文件和配置
<?php return array( //链接数据库的方式:见DatabaseAction.class.php //主从数据库的配置(Common/convention.php) //1.开启数据库的分布式 // 'DB_DEPLOY_TYPE'=> 1, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) //2.必须要做数据库服务器中进行相应的配置 //百度设置数据库集群 //3.读写分离(默认是第一台服务器是写入服务器,其他的服务器的读服务器) // 'DB_RW_SEPARATE'=> true,// 数据库读写是否分离 主从式有效 //ThinkPHP默认的字符集是utf8,不要加中划线- // 'DB_FIELDTYPE_CHECK'=> false, // 是否进行字段类型检查 // 'DB_FIELDS_CACHE' => true, // 启用字段缓存 // 'DB_CHARSET' => 'utf8',// 数据库编码默认采用utf8 //由于数据库的链接需要多个项目来使用可以在一个页面中定义个公共的配置项,返回一个array数组 //ThinkPHP中的db目录:Lib/Think/Db/Db.class.php //连接数据库设置 'DB_TYPE'=>'mysql', 'DB_HOST'=>'localhost', //设置主从数据时用 //'DB_HOST'=>'localhost,192.168.123.1', 'DB_NAME'=>'thinkphp', //设置主从数据时若名字不同 //'DB_NAME'=>'hibernate,ant,thinkphp', 'DB_USER'=>'root', 'DB_PWD'=>'root', //如果未修改可以不用填写 'DB_POST'=>'3306', 'DB_PREFIX'=>'tb_', ); ?>
action
<?php class UserdbAction extends Action{ public function index(){ $user=M('User'); $list=$user->select(); $this->assign('title','thinkphp演示'); $this->assign('alist',$list); $this->display(); } public function add(){ //D是需要些Model的,M不需要写 $user=D('User'); if ($vo=$user->create()){ echo 'create成功'; $user->password=md5($user->password); $user->createtime=time(); //扩展函数需要进加载之后使用 load('extend'); $user->createip=get_client_ip(); if ($user->add()){ $this->success("用户注册成功"); }else{ $this->error($user->getError()); } }else{ echo 'create失败'; $this->error($user->getError()); } } public function del(){ //D是需要些Model的,M不需要写 $user=D('User'); if ($vo=$user->delete($_GET['id'])){ $this->success("用户删除成功"); }else{ $this->error($user->getError()); } } public function edit(){ $user=M('user'); $id=$_GET['id']; $list=$user->where("id=$id")->find(); $this->assign('user',$list); $this->assign('title','编辑用户'); $this->display(); } public function update(){ $user=M('user'); if ($vo=$user->create()){ if ($lineNum=$user->save()){ $this->success("用户更新成功"); }else{ $this->error($user->getError()); } }else{ $this->error($user->getError()); } } } ?>
model
<?php class UserModel extends Model{ function modelTest(){ echo '测试的跨模型操作,调用模型中的方法'; } } ?>
html:
index.html
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title><!--{$title}--></title>
edit.html
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title><!--{$title}--></title>

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
