PHP에서 싱글톤 패턴을 구현하는 방법과 의미

墨辰丷
풀어 주다: 2023-03-29 13:54:02
원래의
1275명이 탐색했습니다.

이 글에서는 주로 PHP에서 싱글턴 모드를 구현하는 방법을 소개하고, 왜 싱글턴 모드를 사용하는지 알려드립니다. 관심 있는 친구들은 참고하시면 됩니다.

1. 싱글턴 모드란 무엇인가요? 1. 의미 싱글톤 모드는 객체 생성 모드로서 특정 클래스의 인스턴스가 하나만 있음을 보장하고, 자신을 인스턴스화하여 이 인스턴스를 전체 시스템에 전역적으로 제공합니다. 인스턴스의 복사본을 생성하지 않지만 싱글톤 클래스 내에 저장된 인스턴스에 대한 참조를 반환합니다.
2. 싱글톤 패턴의 세 가지 핵심 사항: (1) 클래스의 유일한 인스턴스를 보유하는 정적 멤버 변수가 필요합니다:
private static $_instance; 외부 프로그램이 새 클래스에서 실행되어 싱글톤 모드의 의미를 잃지 않도록 하려면 Private로 선언해야 합니다.

private function __construct()  
{  
  $this->_db = pg_connect('xxxx'); 
}  
private function __clone() 
{ 
}//覆盖__clone()方法,禁止克隆
로그인 후 복사

(3) 이 인스턴스에 액세스하려면 공개 정적 메서드(일반적으로 getInstance 메서드)를 제공해야 합니다. 유일한 인스턴스에 대한 참조

public static function getInstance()  
{  
  if(! (self::$_instance instanceof self) )  
  {  
    self::$_instance = new self();  
  } 
  return self::$_instance;  
 
}
로그인 후 복사

2. 싱글톤 모드를 사용하는 이유는 무엇입니까?缺1, PHP 단점:
PHP 언어는 해석된 스크립트 언어입니다. 이 운영 메커니즘은 각 PHP 페이지가 설명되고 실행된 후 모든 관련 리소스를 재활용합니다. 즉, PHP는 언어 수준에서 객체를 메모리에 상주시킬 수 있는 방법이 없습니다. 이는 asp.net 및 Java와 같은 컴파일된 유형과 다릅니다. 예를 들어 Java에서는 싱글톤이 수명 주기 내내 존재합니다. 변수는 페이지 간 수준이며 애플리케이션 수명 주기에서 이 인스턴스를 고유하게 만들 수 있습니다. 그러나 PHP에서는 전역 변수이든 클래스의 정적 멤버이든 모든 변수는 페이지 수준입니다. 페이지가 실행될 때마다 새 개체가 다시 설정되고 페이지가 실행된 후에 지워집니다. PHP 싱글턴 모드는 의미가 없는 것 같으니, 단일 페이지 수준 요청에서 여러 애플리케이션 시나리오가 발생하고 동일한 개체 리소스를 공유해야 하는 경우에만 PHP 싱글턴 모드가 매우 의미가 있다고 생각합니다.

2. PHP에서 싱글턴 모드를 적용하는 경우:

(1) 애플리케이션과 데이터베이스 간의 상호 작용 애플리케이션에서는 데이터베이스를 통해 데이터베이스에 연결하는 등 수많은 데이터베이스 작업이 발생합니다. 사용 싱글톤 모드는 각각의 새로운 작업이 메모리 리소스와 시스템 리소스를 소비하기 때문에 많은 수의 새로운 작업을 방지할 수 있습니다. (2) 구성 정보 제어 시스템의 특정 구성 정보를 전역적으로 제어하기 위해 클래스가 필요한 경우 싱글톤 모드를 쉽게 구현할 수 있습니다.


3. 싱글톤 모드를 구현하는 방법은 무엇입니까?

1. 일반 데이터베이스 액세스 예:

<?php 
...... 
//初始化一个数据库句柄 
$db = new DB(...); 
 
//添加用户信息 
$db->addUserInfo(...); 
 
...... 
 
//在函数中访问数据库,查找用户信息 
function getUserInfo() 
{ 
  $db = new DB(...);//再次new 数据库类,和数据库建立连接 
  $db = query(....);//根据查询语句访问数据库 
} 
 
?>
로그인 후 복사

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(...);  
 
?>
로그인 후 복사
다음 코드는 싱글톤 모드를 사용하는 PDO 작업 데이터베이스 클래스를 캡슐화한 것입니다.
<?php
/**
 * MyPDO
 */
class MyPDO
{
  protected static $_instance = null;
  protected $dbName = &#39;&#39;;
  protected $dsn;
  protected $dbh;
  
  /**
   * 构造
   * 
   * @return MyPDO
   */
  private function __construct($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset)
  {
    try {
      $this->dsn = &#39;mysql:host=&#39;.$dbHost.&#39;;dbname=&#39;.$dbName;
      $this->dbh = new PDO($this->dsn, $dbUser, $dbPasswd);
      $this->dbh->exec(&#39;SET character_set_connection=&#39;.$dbCharset.&#39;, character_set_results=&#39;.$dbCharset.&#39;, character_set_client=binary&#39;);
    } catch (PDOException $e) {
      $this->outputError($e->getMessage());
    }
  }
  
  /**
   * 防止克隆
   * 
   */
  private function __clone() {}
  
  /**
   * Singleton instance
   * 
   * @return Object
   */
  public static function getInstance($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset)
  {
    if (self::$_instance === null) {
      self::$_instance = new self($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset);
    }
    return self::$_instance;
  }
  
  /**
   * Query 查询
   *
   * @param String $strSql SQL语句
   * @param String $queryMode 查询方式(All or Row)
   * @param Boolean $debug
   * @return Array
   */
  public function query($strSql, $queryMode = &#39;All&#39;, $debug = false)
  {
    if ($debug === true) $this->debug($strSql);
    $recordset = $this->dbh->query($strSql);
    $this->getPDOError();
    if ($recordset) {
      $recordset->setFetchMode(PDO::FETCH_ASSOC);
      if ($queryMode == &#39;All&#39;) {
        $result = $recordset->fetchAll();
      } elseif ($queryMode == &#39;Row&#39;) {
        $result = $recordset->fetch();
      }
    } else {
      $result = null;
    }
    return $result;
  }
  
  /**
   * Update 更新
   *
   * @param String $table 表名
   * @param Array $arrayDataValue 字段与值
   * @param String $where 条件
   * @param Boolean $debug
   * @return Int
   */
  public function update($table, $arrayDataValue, $where = &#39;&#39;, $debug = false)
  {
    $this->checkFields($table, $arrayDataValue);
    if ($where) {
      $strSql = &#39;&#39;;
      foreach ($arrayDataValue as $key => $value) {
        $strSql .= ", `$key`=&#39;$value&#39;";
      }
      $strSql = substr($strSql, 1);
      $strSql = "UPDATE `$table` SET $strSql WHERE $where";
    } else {
      $strSql = "REPLACE INTO `$table` (`".implode(&#39;`,`&#39;, array_keys($arrayDataValue))."`) VALUES (&#39;".implode("&#39;,&#39;", $arrayDataValue)."&#39;)";
    }
    if ($debug === true) $this->debug($strSql);
    $result = $this->dbh->exec($strSql);
    $this->getPDOError();
    return $result;
  }
  
  /**
   * Insert 插入
   *
   * @param String $table 表名
   * @param Array $arrayDataValue 字段与值
   * @param Boolean $debug
   * @return Int
   */
  public function insert($table, $arrayDataValue, $debug = false)
  {
    $this->checkFields($table, $arrayDataValue);
    $strSql = "INSERT INTO `$table` (`".implode(&#39;`,`&#39;, array_keys($arrayDataValue))."`) VALUES (&#39;".implode("&#39;,&#39;", $arrayDataValue)."&#39;)";
    if ($debug === true) $this->debug($strSql);
    $result = $this->dbh->exec($strSql);
    $this->getPDOError();
    return $result;
  }
  
  /**
   * Replace 覆盖方式插入
   *
   * @param String $table 表名
   * @param Array $arrayDataValue 字段与值
   * @param Boolean $debug
   * @return Int
   */
  public function replace($table, $arrayDataValue, $debug = false)
  {
    $this->checkFields($table, $arrayDataValue);
    $strSql = "REPLACE INTO `$table`(`".implode(&#39;`,`&#39;, array_keys($arrayDataValue))."`) VALUES (&#39;".implode("&#39;,&#39;", $arrayDataValue)."&#39;)";
    if ($debug === true) $this->debug($strSql);
    $result = $this->dbh->exec($strSql);
    $this->getPDOError();
    return $result;
  }
  
  /**
   * Delete 删除
   *
   * @param String $table 表名
   * @param String $where 条件
   * @param Boolean $debug
   * @return Int
   */
  public function delete($table, $where = &#39;&#39;, $debug = false)
  {
    if ($where == &#39;&#39;) {
      $this->outputError("&#39;WHERE&#39; is Null");
    } else {
      $strSql = "DELETE FROM `$table` WHERE $where";
      if ($debug === true) $this->debug($strSql);
      $result = $this->dbh->exec($strSql);
      $this->getPDOError();
      return $result;
    }
  }
  
  /**
   * execSql 执行SQL语句
   *
   * @param String $strSql
   * @param Boolean $debug
   * @return Int
   */
  public function execSql($strSql, $debug = false)
  {
    if ($debug === true) $this->debug($strSql);
    $result = $this->dbh->exec($strSql);
    $this->getPDOError();
    return $result;
  }
  
  /**
   * 获取字段最大值
   * 
   * @param string $table 表名
   * @param string $field_name 字段名
   * @param string $where 条件
   */
  public function getMaxValue($table, $field_name, $where = &#39;&#39;, $debug = false)
  {
    $strSql = "SELECT MAX(".$field_name.") AS MAX_VALUE FROM $table";
    if ($where != &#39;&#39;) $strSql .= " WHERE $where";
    if ($debug === true) $this->debug($strSql);
    $arrTemp = $this->query($strSql, &#39;Row&#39;);
    $maxValue = $arrTemp["MAX_VALUE"];
    if ($maxValue == "" || $maxValue == null) {
      $maxValue = 0;
    }
    return $maxValue;
  }
  
  /**
   * 获取指定列的数量
   * 
   * @param string $table
   * @param string $field_name
   * @param string $where
   * @param bool $debug
   * @return int
   */
  public function getCount($table, $field_name, $where = &#39;&#39;, $debug = false)
  {
    $strSql = "SELECT COUNT($field_name) AS NUM FROM $table";
    if ($where != &#39;&#39;) $strSql .= " WHERE $where";
    if ($debug === true) $this->debug($strSql);
    $arrTemp = $this->query($strSql, &#39;Row&#39;);
    return $arrTemp[&#39;NUM&#39;];
  }
  
  /**
   * 获取表引擎
   * 
   * @param String $dbName 库名
   * @param String $tableName 表名
   * @param Boolean $debug
   * @return String
   */
  public function getTableEngine($dbName, $tableName)
  {
    $strSql = "SHOW TABLE STATUS FROM $dbName WHERE Name=&#39;".$tableName."&#39;";
    $arrayTableInfo = $this->query($strSql);
    $this->getPDOError();
    return $arrayTableInfo[0][&#39;Engine&#39;];
  }
  
  /**
   * beginTransaction 事务开始
   */
  private function beginTransaction()
  {
    $this->dbh->beginTransaction();
  }
  
  /**
   * commit 事务提交
   */
  private function commit()
  {
    $this->dbh->commit();
  }
  
  /**
   * rollback 事务回滚
   */
  private function rollback()
  {
    $this->dbh->rollback();
  }
  
  /**
   * transaction 通过事务处理多条SQL语句
   * 调用前需通过getTableEngine判断表引擎是否支持事务
   *
   * @param array $arraySql
   * @return Boolean
   */
  public function execTransaction($arraySql)
  {
    $retval = 1;
    $this->beginTransaction();
    foreach ($arraySql as $strSql) {
      if ($this->execSql($strSql) == 0) $retval = 0;
    }
    if ($retval == 0) {
      $this->rollback();
      return false;
    } else {
      $this->commit();
      return true;
    }
  }
  /**
   * checkFields 检查指定字段是否在指定数据表中存在
   *
   * @param String $table
   * @param array $arrayField
   */
  private function checkFields($table, $arrayFields)
  {
    $fields = $this->getFields($table);
    foreach ($arrayFields as $key => $value) {
      if (!in_array($key, $fields)) {
        $this->outputError("Unknown column `$key` in field list.");
      }
    }
  }
  
  /**
   * getFields 获取指定数据表中的全部字段名
   *
   * @param String $table 表名
   * @return array
   */
  private function getFields($table)
  {
    $fields = array();
    $recordset = $this->dbh->query("SHOW COLUMNS FROM $table");
    $this->getPDOError();
    $recordset->setFetchMode(PDO::FETCH_ASSOC);
    $result = $recordset->fetchAll();
    foreach ($result as $rows) {
      $fields[] = $rows[&#39;Field&#39;];
    }
    return $fields;
  }
  
  /**
   * getPDOError 捕获PDO错误信息
   */
  private function getPDOError()
  {
    if ($this->dbh->errorCode() != &#39;00000&#39;) {
      $arrayError = $this->dbh->errorInfo();
      $this->outputError($arrayError[2]);
    }
  }
  
  /**
   * debug
   * 
   * @param mixed $debuginfo
   */
  private function debug($debuginfo)
  {
    var_dump($debuginfo);
    exit();
  }
  
  /**
   * 输出错误信息
   * 
   * @param String $strErrMsg
   */
  private function outputError($strErrMsg)
  {
    throw new Exception(&#39;MySQL Error: &#39;.$strErrMsg);
  }
  
  /**
   * destruct 关闭数据库连接
   */
  public function destruct()
  {
    $this->dbh = null;
  }
}
?>
로그인 후 복사

전화 방법 :

<?php
require &#39;MyPDO.class.php&#39;;
$db = MyPDO::getInstance(&#39;localhost&#39;, &#39;root&#39;, &#39;123456&#39;, &#39;test&#39;, &#39;utf8&#39;);
$db->query("select count(*) frome table");
$db->destruct();
?>
로그인 후 복사

요약 : 위 내용이 이 글의 전체 내용입니다. 모든 분들의 학습에 도움이 되었으면 좋겠습니다.

관련 권장 사항:

php

iPhone을 뒤집어 찍은 거꾸로된 사진 인식PHP는 로그인 인증 코드 확인 기능을 구현합니다.

PHP는 Tencent Cloud COS 인터페이스에 필요한 요청 서명을 생성합니다.

위 내용은 PHP에서 싱글톤 패턴을 구현하는 방법과 의미의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!