This article mainly introduces the TP5 singleton mode operation model, which has certain reference value. Now I share it with everyone. Friends in need can refer to it
1. Create database and database configuration
1. The database design is as follows
SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for users -- ---------------------------- DROP TABLE IF EXISTS `users`; CREATE TABLE `users` ( `u_id` int(255) NOT NULL AUTO_INCREMENT, `u_name` varchar(50) NOT NULL, `u_age` int(3) DEFAULT NULL, `u_sex` tinyint(1) DEFAULT NULL, PRIMARY KEY (`u_id`) ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
2. database.php
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- return [ // 数据库类型 'type' => 'mysql', // 服务器地址 'hostname' => '127.0.0.1', // 数据库名 'database' => 'singletons', // 用户名 'username' => 'root', // 密码 'password' => '123456', // 端口 'hostport' => '3306', // 连接dsn 'dsn' => '', // 数据库连接参数 'params' => [], // 数据库编码默认采用utf8 'charset' => 'utf8', // 数据库表前缀 'prefix' => 'u_', // 数据库调试模式 'debug' => true, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) 'deploy' => 0, // 数据库读写是否分离 主从式有效 'rw_separate' => false, // 读写分离后 主服务器数量 'master_num' => 1, // 指定从服务器序号 'slave_no' => '', // 是否严格检查字段是否存在 'fields_strict' => true, // 数据集返回类型 'resultset_type' => 'array', // 自动写入时间戳字段 'auto_timestamp' => false, // 时间字段取出后的默认时间格式 'datetime_format' => 'Y-m-d H:i:s', // 是否需要进行SQL性能分析 'sql_explain' => false, ];
Second, the separation of MVC
1.Controller
Create a new controller: Users.php
2.Model
Create a new model file Users.php
3.View
Create a new users folder and create a new index. html file
3. Code implementation of tp5 singleton mode
1. Why use singleton mode
Using singleton mode to separate logical processing and database operations can be very easy Greatly improve mysql's sql processing capabilities, and easy to maintain
2. The controller only processes logic, and the model only processes database operations
3. Example, the code is as follows
HTML:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>TP5.0单例模式</title> <link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <p style="margin-top:20%;"> <form class="form-horizontal" role="form" method="POST" action="{:url('users/add')}"> <p class="form-group"> <label for="firstname" class="col-sm-2 control-label">Id</label> <p class="col-sm-6"> <input type="text" class="form-control" name="id" id="id" placeholder="id"> </p> </p> <p class="form-group"> <label for="lastname" class="col-sm-2 control-label">Name</label> <p class="col-sm-6"> <input type="text" class="form-control" name="name" id="name" placeholder="Name"> </p> </p> <p class="form-group"> <p class="col-sm-offset-2 col-sm-10"> <p class="checkbox"> <label> <input type="checkbox"> Remember me </label> </p> </p> </p> <p class="form-group"> <p class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Go</button> </p> </p> </form> </p> </body> </html>
Routing settings
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- Route::rule('add','users/add','GET'); // 添加 Route::rule('del','users/del','GET'); // 删除 Route::rule('update','users/update','GET'); // 更新 Route::rule('query','users/query','GET');// 查询 Route::rule('batchupdate','users/batchupdate','GET'); // 更新多个
Controller
<?php namespace app\index\controller; use app\index\model\Users as UsersModel; use think\Controller; use think\Db; class Users extends Controller { /** * 模板渲染 */ public function index() { return view('index'); } /** * 添加一条数据 */ public function add() { $u_id = intval(input('id')); $u_name = input('name'); $u_age = 18; $u_sex = 0; $insertOne = UsersModel::insertOne($u_id,$u_name,$u_age,$u_sex); if($insertOne) { $this->success("插入".$u_name."成功"); } else{ $this->error("插入".$u_name."失败"); } } /** * 删除一条数据(硬删除) */ public function del() { $u_id = intval(input('id')); $delOne = UsersModel::deleteOne($u_id); if($delOne) { $this->success("删除".$u_id."成功"); } else{ $this->error("删除".$u_id."失败"); } } /** * 更新 */ public function update() { $u_id = intval(input('id')); $u_age = 18; $updateOne = UsersModel::updateOne($u_id,$u_age); if($updateOne) { $this->success("更新".$u_id."的年龄为".$u_age."成功"); } else{ $this->error("更新".$u_id."的年龄为".$u_age."失败"); } } /** * 查询 */ public function query() { $filed = "u_id,u_age"; //多个字段以逗号隔开 $u_id = ""; $query = UsersModel::query($filed,$u_id); dump($query); } /** * 批量修改 */ public function batchupdate() { $array = array(array('u_id'=>1,'u_name'=>'deng','u_age'=>18,'u_sex'=>1),array('u_id'=>2,'u_name'=>'yuan','u_age'=>19,'u_sex'=>2)); $updateall = UsersModel::batchUpdate($arr); if($updateall) { $this->success("success"); } else{ $this->error("error"); } } }
Model SQL processing uses static modification
<?php namespace app\index\model; use think\Model; use think\Db; /** * 使用静态方法 static 而不是 public 在controller里面不用new 直接用 会方便很多 */ class Users extends Model { private static $instance; protected $defaultField = 'danli'; private function __clone(){} //禁止被克隆 /** * 单例 */ public static function getInstance() { if(!(self::$instance instanceof self)){ self::$instance = new static(); } return self::$instance; } /** * 添加一条数据 */ public static function insertOne($uid,$uname,$uage,$usex) { $inserttheone = self::getInstance()->execute("insert into users(u_id,u_name,u_age,u_sex) value(".$uid.",'".$uname."',".$uage.",".$usex.")"); if($inserttheone) { return true; } else{ return false; } } /** * 删除一条数据 */ public static function deleteOne($uid) { $delone = self::getInstance()->execute("delete from users where u_id = ".$uid.""); if($delone) { return true; } else{ return false; } } /** * 修改一条数据 */ public static function updateOne($uid,$age) { $updateone = self::getInstance()->execute("update users set u_age = ".$age." where u_uid = ".$uid.""); if($updateone) { return true; } else{ return false; } } /** * 查询 */ public static function query($defaultField,$uid) { if($defaultField == '' || empty($defaultField) || is_null($defaultField)){ $defaultField = '*'; } if($uid == '' || empty($uid) || is_null($uid)){ $uid = ''; } else{ $uid = "where u_id = $uid"; } return self::getInstance()->query("select $defaultField from users $uid"); } /** * 批量修改 */ public static function batchUpdate($arr) { foreach ($arr as $key => $value) { $updatearr = self::getInstance()->execute("update users set u_name = '".$value['u_name']."',u_age = ".$value['u_age'].",u_sex = ".$value['u_sex']." where u_uid = ".$uid.""); if($updatearr) { return true; } else{ return false; } } } }
4. The above is some SQL that uses singleton mode to process model Processing, in tp5, the controller table name model can be used directly as long as it corresponds to one-to-one, which is relatively convenient.
Related recommendations:
Tp5 project modification database
The above is the detailed content of TP5 singleton mode operation model. For more information, please follow other related articles on the PHP Chinese website!

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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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.

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

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
