This article mainly introduces about TP5 single-case mode operation model, has a certain reference value, now share to everyone, have the need for friends can refer to
I. CREATE DATABASE and Database configuration
1. The database is designed 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 (a) NOT null, ' u_age ' int (3) Default NULL, ' u_sex ' tinyint (1) default NULL, PRIMARY KEY (' u_id ')) Engine=myisam auto_increment=5 default CHAR Set=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 [//Database type ' type ' = ' mysql ',//server address ' hostname ' = ' 127.0.0.1 ',//database name ' Database ' = ' singletons ',//username ' username ' = ' root ',//password ' password ' + ' 123456 ',//Port ' hostport ' = ' 3306 ',//Connect DSN ' DSN ' = ',//database connection parameter ' params ' = = [],//Database encoding default with UTF8' CharSet ' = ' utf8 ',//database table prefix ' prefix ' = ' u_ ',//Database debug mode ' Debug ' = Tru E,//Database deployment method: 0 Centralized (single server), 1 distributed (Master-slave server) ' deploy ' + 0,///database read/write whether separate master-slave effective ' rw_separate ' and false,//read/write after separation Number of primary servers ' Master_num ' + 1,//Specify from server serial number ' slave_no ' = ', '//whether the field is strictly checked for the presence of ' fields_strict ' = = True,//Data set return type ' resultset_type ' = ' array ',//auto-write timestamp field ' auto_timestamp ' = false,//time Word The default time format after the segment is removed ' Datetime_format ' + ' y-m-d h:i:s ',//Do you need to perform SQL performance analysis ' sql_explain ' and ' = False ';
Two, the separation of the MVC three
1.Controller
New controller:Users.php
2.Model
New Model File users.php
3.View
Create a new Users folder and create a new index.html file
Three, TP5 the code realization of single case pattern
1. Why use Singleton mode
Using singleton mode to separate logical processing from database operation greatly improves MySQL's SQL processing power and is easy to maintain
2.controller processing logic only, model only handles database operations
3. Example, the code is as follows
Html:
<! DOCTYPE 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 '); Add Route::rule (' del ', ' Users/del ', ' GET '); Delete route::rule (' Update ', ' users/update ', ' GET '); Update route::rule (' query ', ' users/query ', ' get ');//Query Route::rule (' batchupdate ', ' users/batchupdate ', ' get '); Update multiple
Controller
<?phpnamespace app\index\controller;use app\index\model\users as Usersmodel;use think\Controller;use think\Db; Class Users extends controller{/** * Template Rendering */Public Function index () {return view (' index '); }/** * Adds a data */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 ("Insert". $u _name. " Success "); } else{$this->error ("Insert". $u _name. " Failure "); }}/** * Delete a piece of data (hard delete) */Public Function del () {$u _id = intval (input (' id ')); $delOne = Usersmodel::d eleteone ($u _id); if ($delOne) {$this->success ("delete". $u _id. " Success "); } else{$this->error ("delete". $u _id. " Failure "); }}/** * UPDATE */Public Function update () {$u _id= Intval (input (' id ')); $u _age = 18; $updateOne = Usersmodel::updateone ($u _id, $u _age); if ($updateOne) {$this->success ("Update". $u _id. " The age of ". $u _age." Success "); } else{$this->error ("Update". $u _id. " The age of ". $u _age." Failure "); }}/** * query */Public Function query () {$filed = "u_id,u_age";//multiple fields separated by commas $u _id = "" ; $query = Usersmodel::query ($filed, $u _id); Dump ($query); }/** * Bulk Modify */Public Function batchupdate () {$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 adornments
<?phpnamespace app\index\model;use think\model;use think\db;/** * Static method is used statically instead of public in controller without new direct use will be convenient very Multiple */class Users extends model{private static $instance; protected $defaultField = ' Danli '; Private Function __clone () {}//Disallow cloning/** * Singleton */public static function getinstance () {if (! Self:: $instance instanceof Self)} {self:: $instance = new static (); } return Self:: $instance; }/** * Add a data */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; }}/** * Delete a data */public static function Deleteone ($uid) {$delone = Self::getinstance ()->ex Ecute ("Delete from users where u_id =". $uid. "); if ($DeLone) {return true; } else{return false; }}/** * Modify a data */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; }}/** * query */public static function query ($defaultField, $uid) {if ($defaultField = = "| | e Mpty ($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"); }/** * Bulk Modify */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; } } }}
Four, the above is the use of a singleton mode to deal with the model of some SQL processing, in the TP5 controller table name model as long as one by one corresponding can be used directly, relatively speaking is more convenient