>  기사  >  백엔드 개발  >  PHP 싱글톤 모드의 장점 분석

PHP 싱글톤 모드의 장점 분석

小云云
小云云원래의
2018-03-03 14:01:021692검색

1. 싱글턴 패턴이란 무엇인가요?

1. 의미
싱글턴 모드는 객체 생성 모드로서 특정 클래스의 인스턴스가 하나만 있음을 보장하고, 자신을 인스턴스화하여 이 인스턴스를 전체 시스템에 전역적으로 제공합니다. 인스턴스의 복사본을 생성하지 않지만 싱글톤 클래스 내에 저장된 인스턴스에 대한 참조를 반환합니다.

2. 싱글턴 패턴의 세 가지 핵심 사항:

(1) 클래스의 유일한 인스턴스를 저장하려면 정적 멤버 변수가 필요합니다.

private static $_instance;




(2). 외부 프로그램이 새 클래스에서 실행되지 않도록 하여 싱글턴 모드의 의미를 잃게 하려면 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. 싱글톤 모드를 사용하는 이유는 무엇입니까?

대부분의 사람들은 싱글턴 패턴의 목적을 문자 그대로 이해하고, 시스템 리소스를 절약하고, 반복적인 인스턴스화를 피하며, 일종의 "가족 계획"이라고 생각합니다. 그리고 PHP는 모든 실행을 완료합니다. 페이지에서 모든 리소스를 지웁니다. 따라서 PHP의 싱글톤은 실제로 실행될 때마다 다시 인스턴스화되어야 하므로 싱글톤의 반복된 인스턴스화의 의미를 잃게 됩니다. 이 측면만으로도 PHP의 싱글톤은 실제로 모든 사람에게 약간 실망스럽습니다. 싱글톤에는 이 기능과 애플리케이션만 있습니까? 대답은 '아니요'입니다. 살펴보겠습니다.

PHP는 주로 데이터베이스 응용 프로그램에 사용되므로 응용 프로그램에서 데이터베이스 작업이 많이 발생합니다. 객체 지향 방식(넌센스)으로 개발할 때 싱글톤 모드를 사용하면 많은 수의 작업을 피할 수 있습니다. 새로운 작업에 의해 소비되는 자원.
특정 구성 정보를 전역적으로 제어하기 위해 시스템에 클래스가 필요한 경우 싱글톤 모드를 사용하여 쉽게 구현할 수 있습니다. 이에 대해서는 zend Framework의 FrontController 부분을 참조하세요.
페이지 요청에서는 모든 코드(예: 데이터베이스 작업 클래스 db)가 하나의 클래스에 집중되어 있기 때문에 디버깅하기 쉽습니다. 클래스에 후크를 설정하고 로그를 출력하여 모든 곳에서 var_dump 및 echo를 방지할 수 있습니다. 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操作数据库类的一个封装,采用了单例模式:


e805f2cab7c01f804689bf075158c337dsn = 'mysql:host='.$dbHost.';dbname='.$dbName;

            $this->dbh = new PDO($this->dsn, $dbUser, $dbPasswd);

            $this->dbh->exec('SET character_set_connection='.$dbCharset.', character_set_results='.$dbCharset.', character_set_client=binary');

        } 7ada43ee74c1dbbf3cd559fccdb665f8catch5db79b134e9f6b82c0b36e0489ee08ed (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

     */

    공개 함수 쿼리($ strSql, $queryMode = '모두', $debug = false)

    {

        if ($debug === true) $this->debug($strSql);

        $recordset = $this->dbh->query($strSql);

$this->getPDOError();

        if ($recordset) {

           $recordset->setFetchMode(PDO::FETCH_ASSOC);

           if ($queryMode == '모두') {

                $result = 정의

        } 그밖에 {

            $result = null;

        }

        return $result;

    }

     

    /**

               * 업데이트 업데이트

                                                                     @ Int

반환*/

    공개 함수 업데이트($table, $arrayDataValue, $where ='', $debug = false)

ㅋㅋㅋ  9860c488cc156446e55f59334874886eforeach5db79b134e9f6b82c0b36e0489ee08ed ($arrayDataValue as $key => $value) {

               $strSql .= ", `$key`='$value'";

            }

            $strSql = b3fe4bd4b856559ca1f3bebe287e1789substr5db79b134e9f6b82c0b36e0489ee08ed($strSql, 1);

           $strSql = "UPDATE `$table` SET $strSql WHERE $where";

        } else {

            $strSql = "REPLACE INTO `$table` (`".implode('`,`', array_keys($arrayDataValue))."`) 값 ('".implode("','", $arrayDataValue )."')";

        }

        if ($debug === true) $this->debug($strSql);

        $result = $this->dbh->exec($strSql );

        $this->getPDOError();

        return $result;

    }

     

    /**T*INSERT 삽입

*@Param String $ Table 테이블 이름

@Param Array $ ArrayDataValue 필드 및 값

*@Param Boolean $ debug

*@Return int

*/

    공용 함수 삽입($table, $arrayDataValue, $debug = false)

    {

        $this->checkFields($table, $arrayDataValue);

        $strSql = "INSERT INTO `$table` (`".implode('`,`', array_keys($arrayDataValue))."`) 값 ('".implode("','", $arrayDataValue)."')" ;

        if ($debug === true) $this->debug($strSql);

        $result = $this->dbh->exec($strSql);

        $this-> getPDOError();

        return $result;

    }

     

    /**ㅋㅋ*/

    공개 함수 교체($table, $arrayDataValue, $debug = false)

    {

        $this- >checkFields($table, $arrayDataValue);

        $strSql = "REPLACE INTO `$table`(`".implode('`,`', array_keys($arrayDataValue))."`) VALUES('". implode("','", $arrayDataValue)."')";

        if ($debug === true) $this->debug($strSql);

        $result = $this->dbh ->exec($strSql);

        $this->getPDOError();

         return $result;

    }

     

    /**

                                                * * @return Int

*/

    공개 함수 delete($table, $where = '', $debug = false)

    {

        if ($where == '') {

          $this->outputError("'WHERE' is Null");

        } 그밖에 {

ㅋㅋㅋ 이거->dbh- >exec($strSql);

            $this->getPDOError();

            $result;

        }

    }

     

    /**

     * execSql 执行SQL语句

     *

ㅋㅋㅋ

    {

        if ($debug == = true) $this->debug($strSql);

        $result = $this->dbh->exec($strSql);

        $this->getPDOError();

        return $result ;

    }

     

    /**

       * 필드의 최대값 가져오기

     *                                                       ​​*/

    공용 함수 getMaxValue($table, $field_name, $where ='', $debug = false)

    {

        $strSql = "최대 선택 (".$field_name.") AS MAX_VALUE FROM $table";

        if ($where != '') $strSql .= " WHERE $where";

        if ($debug === true) $this- >debug($strSql);

        $arrTemp = $this->query($strSql, 'Row');

        $maxValue = $arrTemp["MAX_VALUE"];

        if ($maxValue == " " || $maxValue == null) {

           $maxValue = 0;

        }

        반환 $maxValue;

    }

     

    /**

       * 지정된 열의 번호를 가져옵니다

     *                           * @param bool $debug

* @return int

      */

    공개 함수 getCount($table, $field_name, $where = '', $debug = false)

    {

        $strSql = "SELECT COUNT($field_name) AS NUM FROM $table";

        if ($where != '') $strSql . = " 어디에서 $where";

        if ($debug === true) $this->debug($strSql);

        $arrTemp = $this->query($strSql, 'Row');

ㅋㅋㅋ        $strSql = "다음에서 테이블 상태 표시 $dbName WHERE Name='".$tableName."'";

       $arrayTableInfo = $this->query($strSql);

        $this->getPDOError();

        반환 $arrayTableInfo[0]['Engine'];

    }

     

    /**

     * startTransaction 거래 시작

    */

    비공개 함수beginTransaction()

    {

        $this->dbh->beginTransaction();

    }

     

    /**

      * 거래 제출 커밋

    */

    비공개 기능 커밋 ()

    {

        $this->dbh->commit();

    }

     

    /**

* 롤백 거래 롤백

*/

    비공개 기능 롤백()

    {

        $this- >dbh->rollback();

    }

     

    /**

           * 트랜잭션은 트랜잭션을 통해 여러 SQL 문을 처리합니다

                                                                                             

      */

    공용 함수 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 지정된 데이터 테이블에 지정된 필드가 있는지 확인합니다.

                   */

    비공개 함수 checkFields($table, $arrayFields)

    {

        $fields = $this->getFields($table);

        foreach ($arrayFields $key로 => $value) {

            if (!in_array($key, $fields)) {

               $this->outputError("필드 목록의 알 수 없는 열 `$key`입니다.");

            }

        }

}

     

    /**​​​*/

ㅋㅋㅋ

        $this- >getPDOError();

        $recordset->setFetchMode(PDO::FETCH_ASSOC);

        $result = $recordset->fetchAll();

        foreach ($result를 $rows로) {

            $fields [] = $rows['Field'];

        }

        return $fields;

    }

     

    /**

      * getPDOError PDO 오류 정보 캡처

    */

    비공개 함수 getPDOError ()

    {

        만약 ($ this->dbh->errorCode() != '00000') {

           $arrayError = $this->dbh->errorInfo();

           $this->outputError($arrayError[2] );

        }

    }

     

    /**

     * debug

     * 

     * @param 혼합 $debuginfo

     */

    비공개 함수 디버그($debuginfo)

    {

        var_d ump($debuginfo);

        exit();

    }

ㅋㅋㅋ  }

     

    /**

         * 오류 메시지 출력

                                            */

    public function destruct()

    {

        $this->dbh = null;

    }

}

?>

ㅋㅋㅋ

'MyPDO.class.php' 필요;

$db = MyPDO::getInstance('localhost', 'root', '123456', 'test', 'utf8');

$db->query("21b2c90260ebfc998bb9f2358b4bc2a8select5db79b134e9f6b82c0b36e0489ee08ed count(*) frome table");

$db->destruct();?>

위 내용은 PHP 싱글톤 모드의 장점 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.