Home Backend Development PHP Tutorial TP5 singleton mode operation model

TP5 singleton mode operation model

May 03, 2018 am 11:11 AM
model operate model

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;
Copy after login

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 [
    // 数据库类型
    &#39;type&#39;            => &#39;mysql&#39;,
    // 服务器地址
    &#39;hostname&#39;        => &#39;127.0.0.1&#39;,
    // 数据库名
    &#39;database&#39;        => &#39;singletons&#39;,
    // 用户名
    &#39;username&#39;        => &#39;root&#39;,
    // 密码
    &#39;password&#39;        => &#39;123456&#39;,
    // 端口
    &#39;hostport&#39;        => &#39;3306&#39;,
    // 连接dsn
    &#39;dsn&#39;             => &#39;&#39;,
    // 数据库连接参数
    &#39;params&#39;          => [],
    // 数据库编码默认采用utf8
    &#39;charset&#39;         => &#39;utf8&#39;,
    // 数据库表前缀
    &#39;prefix&#39;          => &#39;u_&#39;,
    // 数据库调试模式
    &#39;debug&#39;           => true,
    // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
    &#39;deploy&#39;          => 0,
    // 数据库读写是否分离 主从式有效
    &#39;rw_separate&#39;     => false,
    // 读写分离后 主服务器数量
    &#39;master_num&#39;      => 1,
    // 指定从服务器序号
    &#39;slave_no&#39;        => &#39;&#39;,
    // 是否严格检查字段是否存在
    &#39;fields_strict&#39;   => true,
    // 数据集返回类型
    &#39;resultset_type&#39;  => &#39;array&#39;,
    // 自动写入时间戳字段
    &#39;auto_timestamp&#39;  => false,
    // 时间字段取出后的默认时间格式
    &#39;datetime_format&#39; => &#39;Y-m-d H:i:s&#39;,
    // 是否需要进行SQL性能分析
    &#39;sql_explain&#39;     => false,
];
Copy after login

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(&#39;users/add&#39;)}">
		<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>
Copy after login

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(&#39;add&#39;,&#39;users/add&#39;,&#39;GET&#39;); // 添加

Route::rule(&#39;del&#39;,&#39;users/del&#39;,&#39;GET&#39;); // 删除

Route::rule(&#39;update&#39;,&#39;users/update&#39;,&#39;GET&#39;); // 更新

Route::rule(&#39;query&#39;,&#39;users/query&#39;,&#39;GET&#39;);// 查询

Route::rule(&#39;batchupdate&#39;,&#39;users/batchupdate&#39;,&#39;GET&#39;); // 更新多个
Copy after login

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(&#39;index&#39;);
    }
    /**
    * 添加一条数据
    */
    public function add()
    {
        $u_id = intval(input(&#39;id&#39;));
        $u_name = input(&#39;name&#39;);
        $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(&#39;id&#39;));
        $delOne = UsersModel::deleteOne($u_id);
        if($delOne)
        {
            $this->success("删除".$u_id."成功");
        }
        else{
            $this->error("删除".$u_id."失败");
        }
    }
    /**
    * 更新
    */
    public function update()
    {
        $u_id = intval(input(&#39;id&#39;));
        $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(&#39;u_id&#39;=>1,&#39;u_name&#39;=>&#39;deng&#39;,&#39;u_age&#39;=>18,&#39;u_sex&#39;=>1),array(&#39;u_id&#39;=>2,&#39;u_name&#39;=>&#39;yuan&#39;,&#39;u_age&#39;=>19,&#39;u_sex&#39;=>2));
        $updateall = UsersModel::batchUpdate($arr);
        if($updateall)
        {
            $this->success("success");
        }
        else{
            $this->error("error");
        }
    }
}
Copy after login

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 = &#39;danli&#39;;
    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.",&#39;".$uname."&#39;,".$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 == &#39;&#39; || empty($defaultField) || is_null($defaultField)){
            $defaultField = &#39;*&#39;;   
        }
        if($uid == &#39;&#39; || empty($uid) || is_null($uid)){
            $uid = &#39;&#39;;   
        }
        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 = &#39;".$value[&#39;u_name&#39;]."&#39;,u_age = ".$value[&#39;u_age&#39;].",u_sex = ".$value[&#39;u_sex&#39;]." where u_uid = ".$uid."");
            if($updatearr)
            {
                return true;
            }
            else{
                return false;
            }
        }
    }
}
Copy after login

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!

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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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 does WeChat's Do Not Disturb mode do? What does WeChat's Do Not Disturb mode do? Feb 23, 2024 pm 10:48 PM

What does WeChat Do Not Disturb mode mean? Nowadays, with the popularity of smartphones and the rapid development of mobile Internet, social media platforms have become an indispensable part of people's daily lives. WeChat is one of the most popular social media platforms in China, and almost everyone has a WeChat account. We can communicate with friends, family, and colleagues in real time through WeChat, share moments in our lives, and understand each other’s current situation. However, in this era, we are also inevitably faced with the problems of information overload and privacy leakage, especially for those who need to focus or

PyCharm usage tutorial: guide you in detail to run the operation PyCharm usage tutorial: guide you in detail to run the operation Feb 26, 2024 pm 05:51 PM

PyCharm is a very popular Python integrated development environment (IDE). It provides a wealth of functions and tools to make Python development more efficient and convenient. This article will introduce you to the basic operation methods of PyCharm and provide specific code examples to help readers quickly get started and become proficient in operating the tool. 1. Download and install PyCharm First, we need to go to the PyCharm official website (https://www.jetbrains.com/pyc

What is sudo and why is it important? What is sudo and why is it important? Feb 21, 2024 pm 07:01 PM

sudo (superuser execution) is a key command in Linux and Unix systems that allows ordinary users to run specific commands with root privileges. The function of sudo is mainly reflected in the following aspects: Providing permission control: sudo achieves strict control over system resources and sensitive operations by authorizing users to temporarily obtain superuser permissions. Ordinary users can only obtain temporary privileges through sudo when needed, and do not need to log in as superuser all the time. Improved security: By using sudo, you can avoid using the root account during routine operations. Using the root account for all operations may lead to unexpected system damage, as any mistaken or careless operation will have full permissions. and

Do Not Disturb Mode Not Working in iPhone: Fix Do Not Disturb Mode Not Working in iPhone: Fix Apr 24, 2024 pm 04:50 PM

Even answering calls in Do Not Disturb mode can be a very annoying experience. As the name suggests, Do Not Disturb mode turns off all incoming call notifications and alerts from emails, messages, etc. You can follow these solution sets to fix it. Fix 1 – Enable Focus Mode Enable focus mode on your phone. Step 1 – Swipe down from the top to access Control Center. Step 2 – Next, enable “Focus Mode” on your phone. Focus Mode enables Do Not Disturb mode on your phone. It won't cause any incoming call alerts to appear on your phone. Fix 2 – Change Focus Mode Settings If there are some issues in the focus mode settings, you should fix them. Step 1 – Open your iPhone settings window. Step 2 – Next, turn on the Focus mode settings

Linux Deploy operation steps and precautions Linux Deploy operation steps and precautions Mar 14, 2024 pm 03:03 PM

LinuxDeploy operating steps and precautions LinuxDeploy is a powerful tool that can help users quickly deploy various Linux distributions on Android devices, allowing users to experience a complete Linux system on their mobile devices. This article will introduce the operating steps and precautions of LinuxDeploy in detail, and provide specific code examples to help readers better use this tool. Operation steps: Install LinuxDeploy: First, install

What to do if you forget to press F2 for win10 boot password What to do if you forget to press F2 for win10 boot password Feb 28, 2024 am 08:31 AM

Presumably many users have several unused computers at home, and they have completely forgotten the power-on password because they have not been used for a long time, so they would like to know what to do if they forget the password? Then let’s take a look together. What to do if you forget to press F2 for win10 boot password? 1. Press the power button of the computer, and then press F2 when turning on the computer (different computer brands have different buttons to enter the BIOS). 2. In the bios interface, find the security option (the location may be different for different brands of computers). Usually in the settings menu at the top. 3. Then find the SupervisorPassword option and click it. 4. At this time, the user can see his password, and at the same time find the Enabled next to it and switch it to Dis.

Huawei Mate60 Pro screenshot operation steps sharing Huawei Mate60 Pro screenshot operation steps sharing Mar 23, 2024 am 11:15 AM

With the popularity of smartphones, the screenshot function has become one of the essential skills for daily use of mobile phones. As one of Huawei's flagship mobile phones, Huawei Mate60Pro's screenshot function has naturally attracted much attention from users. Today, we will share the screenshot operation steps of Huawei Mate60Pro mobile phone, so that everyone can take screenshots more conveniently. First of all, Huawei Mate60Pro mobile phone provides a variety of screenshot methods, and you can choose the method that suits you according to your personal habits. The following is a detailed introduction to several commonly used interceptions:

Should I shut down my laptop every time? Should I shut down my laptop every time? Feb 19, 2024 pm 12:09 PM

Windows laptops come with hibernation and shutdown options. When you put your laptop into sleep mode, it enters a low-power mode and you can continue working in any way you left it. If you shut down your laptop, you need to close all programs and your work and start over. If you want to take a break from your laptop throughout the day, sleep mode or hibernation mode is a good option. What about closing the door? Should I shut down my laptop every time? Let's find out. Should I shut down my laptop every time? It may be a good idea to turn off your laptop to save energy and extend the life of the device, especially if it is not used for an extended period of time. But during the day, it’s a good idea to put your laptop into sleep mode to continue your tasks

See all articles