Home  >  Article  >  Backend Development  >  TP5 singleton mode operation model

TP5 singleton mode operation model

不言
不言Original
2018-05-03 11:11:323254browse

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 [
    // 数据库类型
    &#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,
];

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>

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;); // 更新多个

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");
        }
    }
}

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;
            }
        }
    }
}

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:
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