Home > Backend Development > PHP Tutorial > One trick to solve PHP singleton pattern analysis and practical combat

One trick to solve PHP singleton pattern analysis and practical combat

慕斯
Release: 2023-04-10 09:54:01
forward
2357 people have browsed it

We have learned so much about PHP. Today we will learn how to solve the PHP singleton mode analysis and practical combat in one step. I wonder if you have fully mastered it. If not, then follow this article Let’s continue learning with this article

1. What is the singleton pattern?

1. Meaning

## As an object creation mode, the singleton mode ensures that there is only one instance of a certain class, and it instantiates itself and provides this instance globally to the entire system. It does not create a copy of the instance, but returns a reference to the instance stored inside the singleton class.

2. Three key points of the singleton pattern:

(1). A static member variable is required to save the only instance of the class:

private static $_instance;
Copy after login

(2). The constructor and clone function must Declare it as private to prevent external programs from new classes and lose the meaning of the singleton mode:

private function __construct() 
{ 
    $this->_db = pg_connect('xxxx');
} 
private function __clone()
{
}//覆盖__clone()方法,禁止克隆
Copy after login

(3). A public static method to access this instance must be provided ( Usually getInstance method), thus returning a reference to the only instance

    public static function getInstance()  
    {  
        if(! (self::$_instance instanceof self) ) 
        {  
            self::$_instance = new self();  
        }
        return self::$_instance;  

    }
Copy after login

2. Why use the singleton mode?

1. PHP Disadvantages:

PHP language is an interpreted scripting language. This operating mechanism allows all related resources to be recycled after each PHP page is interpreted and executed. In other words, PHP has no way to make an object resident in memory at the language level. This is different from compiled types such as asp.net and Java. For example, in Java, a singleton will always exist throughout the life cycle of the application. Variables are cross-page level and can truly make this instance unique in the application life cycle. However, in PHP, all variables, whether they are global variables or static members of the class, are page-level. Every time the page is executed, a new object will be re-established and will be cleared after the page is executed. It seems that PHP The singleton mode is meaningless, so I think the PHP singleton mode is very meaningful only when multiple application scenarios occur in a single page-level request and need to share the same object resource.

2. Application occasions of singleton mode in PHP:

(1), application and database interaction

## An application will There are a large number of database operations, such as connecting to the database through a database handle. Using the singleton mode can avoid a large number of new operations, because each new operation consumes memory resources and system resources.

(2), control configuration information

如果系统中需要有一个类来全局控制某些配置信息, 那么使用单例模式可以很方便的实现.

三、如何实现单例模式?

1、普通的数据库访问例子:

<?php
......
//初始化一个数据库句柄
$db = new DB(...);

//添加用户信息
$db->addUserInfo(...);

......

//在函数中访问数据库,查找用户信息
function getUserInfo()
{
    $db = new DB(...);//再次new 数据库类,和数据库建立连接
    $db = query(....);//根据查询语句访问数据库
}

?>
Copy after login

2、应用单例模式对数据库进行操作:

<?php

class DB  
{  
    private $_db;  
    private static $_instance;  
  
    private function __construct(...)  
    {  
        $this->_db = pg_connect(...);//postgrsql  
    }  
  
    private function __clone() {};  //覆盖__clone()方法,禁止克隆  
  
    public static function getInstance()  
    {  
        if(! (self::$_instance instanceof self) ) {  
            self::$_instance = new self();  
        }  
        return self::$_instance;  
    }  
  
    

    public function addUserInfo(...)
    {

   

    }

     public function getUserInfo(...)
    { 

    }

}

//test

$db = DB::getInstance();

$db->addUserInfo(...);

$db->getUserInfo(...);


?>
Copy after login

3、深入理解

<?php
class db {
	public $conn;
	public static $sql;
	public static $instance=null;
	private function __construct(){
		require_once(&#39;db.config.php&#39;);
		$this->conn = mysql_connect($db[&#39;host&#39;],$db[&#39;user&#39;],$db[&#39;password&#39;]);
		if(!mysql_select_db($db[&#39;database&#39;],$this->conn)){
			echo "失败";
		};
		mysql_query(&#39;set names utf8&#39;,$this->conn);		
	}
	public static function getInstance(){
		if(is_null(self::$instance)){
			self::$instance = new db;
		}
		return self::$instance;
	}
	/**
	 * 查询数据库
	 */
	public function select($table,$condition=array(),$field = array()){
		$where=&#39;&#39;;
		if(!empty($condition)){
			
			foreach($condition as $k=>$v){
				$where.=$k."=&#39;".$v."&#39; and ";
			}
			$where=&#39;where &#39;.$where .&#39;1=1&#39;;
		}
		$fieldstr = &#39;&#39;;
		if(!empty($field)){
			
			foreach($field as $k=>$v){
				$fieldstr.= $v.&#39;,&#39;;
			}
			 $fieldstr = rtrim($fieldstr,&#39;,&#39;);
		}else{
			$fieldstr = &#39;*&#39;;
		}
		self::$sql = "select {$fieldstr} from {$table} {$where}";
		$result=mysql_query(self::$sql,$this->conn);
		$resuleRow = array();
		$i = 0;
		while($row=mysql_fetch_assoc($result)){
			foreach($row as $k=>$v){
				$resuleRow[$i][$k] = $v;
			}
			$i++;
		}
		return $resuleRow;
	}
	/**
	 * 添加一条记录
	 */
	 public function insert($table,$data){
	 	$values = &#39;&#39;;
	 	$datas = &#39;&#39;;
	 	foreach($data as $k=>$v){
	 		$values.=$k.&#39;,&#39;;
	 		$datas.="&#39;$v&#39;".&#39;,&#39;;
	 	}
	 	$values = rtrim($values,&#39;,&#39;);
	 	$datas   = rtrim($datas,&#39;,&#39;);
	 	self::$sql = "INSERT INTO  {$table} ({$values}) VALUES ({$datas})";
		if(mysql_query(self::$sql)){
			return mysql_insert_id();
		}else{
			return false;
		};
	 }
	 /**
	  * 修改一条记录
	  */
	public function update($table,$data,$condition=array()){
		$where=&#39;&#39;;
		if(!empty($condition)){
			
			foreach($condition as $k=>$v){
				$where.=$k."=&#39;".$v."&#39; and ";
			}
			$where=&#39;where &#39;.$where .&#39;1=1&#39;;
		}
		$updatastr = &#39;&#39;;
		if(!empty($data)){
			foreach($data as $k=>$v){
				$updatastr.= $k."=&#39;".$v."&#39;,";
			}
			$updatastr = &#39;set &#39;.rtrim($updatastr,&#39;,&#39;);
		}
		self::$sql = "update {$table} {$updatastr} {$where}";
		return mysql_query(self::$sql);
	}
	/**
	 * 删除记录
	 */
	 public function delete($table,$condition){
	 	$where=&#39;&#39;;
		if(!empty($condition)){
			
			foreach($condition as $k=>$v){
				$where.=$k."=&#39;".$v."&#39; and ";
			}
			$where=&#39;where &#39;.$where .&#39;1=1&#39;;
		}
		self::$sql = "delete from {$table} {$where}";
		return mysql_query(self::$sql);
		
	 }
	
	public static function getLastSql(){
		echo self::$sql;
	}
	
	
	
}

$db = db::getInstance();
//$list = $db->select(&#39;demo&#39;,array(&#39;name&#39;=>&#39;tom&#39;,&#39;password&#39;=>&#39;ds&#39;),array(&#39;name&#39;,&#39;password&#39;));
//echo $db->insert(&#39;demo&#39;,array(&#39;name&#39;=>&#39;最近你啦&#39;,&#39;password&#39;=>&#39;123&#39;));
//echo $db->update(&#39;demo&#39;,array("name"=>&#39;xxx&#39;,"password"=>&#39;123&#39;),array(&#39;id&#39;=>1));
echo $db->delete(&#39;demo&#39;,array(&#39;id&#39;=>&#39;2&#39;));
db::getLastSql();
echo "<pre class="brush:php;toolbar:false">";
?>
Copy after login

推荐学习:《PHP视频教程

The above is the detailed content of One trick to solve PHP singleton pattern analysis and practical combat. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:csdn.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template