PHP 单例 PDO

发布于 2024-09-18 20:16:06 字数 1852 浏览 5 评论 0原文

来自 http://www.php.net/manual/en/class.pdo。 php

###### config.ini ######
db_driver=mysql
db_user=root
db_password=924892xp

[dsn]
host=localhost
port=3306
dbname=localhost

[db_options]
PDO::MYSQL_ATTR_INIT_COMMAND=set names utf8

[db_attributes]
ATTR_ERRMODE=ERRMODE_EXCEPTION
############

<?php class Database {
    private static $link = null ;

    private static function getLink ( ) {
        if ( self :: $link ) {
            return self :: $link ;
        }

        $ini = _BASE_DIR . "config.ini" ;
        $parse = parse_ini_file ( $ini , true ) ;

        $driver = $parse [ "db_driver" ] ;
        $dsn = "${driver}:" ;
        $user = $parse [ "db_user" ] ;
        $password = $parse [ "db_password" ] ;
        $options = $parse [ "db_options" ] ;
        $attributes = $parse [ "db_attributes" ] ;

        foreach ( $parse [ "dsn" ] as $k => $v ) {
            $dsn .= "${k}=${v};" ;
        }

        self :: $link = new PDO ( $dsn, $user, $password, $options ) ;

        foreach ( $attributes as $k => $v ) {
            self :: $link -> setAttribute ( constant ( "PDO::{$k}" )
                , constant ( "PDO::{$v}" ) ) ;
        }

        return self :: $link ;
    }

    public static function __callStatic ( $name, $args ) {
        $callback = array ( self :: getLink ( ), $name ) ;
        return call_user_func_array ( $callback , $args ) ;
    }
} ?>

<?php // examples
$stmt = Database :: prepare ( "SELECT 'something' ;" ) ;
$stmt -> execute ( ) ;
var_dump ( $stmt -> fetchAll ( ) ) ;
$stmt -> closeCursor ( ) ;
?>

我的问题是:

什么是单例?

静态是什么意思/做什么?

public static function __callStatic ( 用于做什么?

如何才能使 PDO 仅在需要时连接到数据库?例如查询或转义?因此,如果类/对象未使用,则它不会连接。

from http://www.php.net/manual/en/class.pdo.php

###### config.ini ######
db_driver=mysql
db_user=root
db_password=924892xp

[dsn]
host=localhost
port=3306
dbname=localhost

[db_options]
PDO::MYSQL_ATTR_INIT_COMMAND=set names utf8

[db_attributes]
ATTR_ERRMODE=ERRMODE_EXCEPTION
############

<?php class Database {
    private static $link = null ;

    private static function getLink ( ) {
        if ( self :: $link ) {
            return self :: $link ;
        }

        $ini = _BASE_DIR . "config.ini" ;
        $parse = parse_ini_file ( $ini , true ) ;

        $driver = $parse [ "db_driver" ] ;
        $dsn = "${driver}:" ;
        $user = $parse [ "db_user" ] ;
        $password = $parse [ "db_password" ] ;
        $options = $parse [ "db_options" ] ;
        $attributes = $parse [ "db_attributes" ] ;

        foreach ( $parse [ "dsn" ] as $k => $v ) {
            $dsn .= "${k}=${v};" ;
        }

        self :: $link = new PDO ( $dsn, $user, $password, $options ) ;

        foreach ( $attributes as $k => $v ) {
            self :: $link -> setAttribute ( constant ( "PDO::{$k}" )
                , constant ( "PDO::{$v}" ) ) ;
        }

        return self :: $link ;
    }

    public static function __callStatic ( $name, $args ) {
        $callback = array ( self :: getLink ( ), $name ) ;
        return call_user_func_array ( $callback , $args ) ;
    }
} ?>

<?php // examples
$stmt = Database :: prepare ( "SELECT 'something' ;" ) ;
$stmt -> execute ( ) ;
var_dump ( $stmt -> fetchAll ( ) ) ;
$stmt -> closeCursor ( ) ;
?>

My questions are:

What is singleton?

What does static mean/do?

What is public static function __callStatic ( used for?

And how can I make it, that PDO only connects to the database when needed? Such as a query or escaping? So if the class/object is unused then it doesn't connect.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

花开浅夏 2024-09-25 20:16:06

单例是一种软件设计模式,它将类的启动限制为一个实例。 http://en.wikipedia.org/wiki/Singleton_pattern

静态表示某物属于类而不是特定实例。在 PHP 中,这也意味着需要使用 :: 调用静态方法,而不是 ->

_callStatic 返回 PDO 链接(如果已经建立)。否则,它首先创建链接,然后返回它。

第四个问题的答案正是单例模式。它确保仅在需要时建立连接一次。

A singleton is a software design pattern that restricts the initiation of a class to one instance. http://en.wikipedia.org/wiki/Singleton_pattern

Static means that something belongs to the class and not a particular instance. In PHP, this also means that a static method needs to be called with :: not ->

_callStatic returns the PDO link if it has already been established. Otherwise, it first creates the link and then returns it.

The answer to your fourth question is precisely the singleton pattern. It ensures that the connection is only set up once, when needed.

与往事干杯 2024-09-25 20:16:06

单例是一个静态函数,它允许您跟踪对象实例,当您使用单例时,您创建了对象的实例,但实例始终与关联的对象保持在一起。

举个例子:

$db1 = new Database();
$db2 = new Database();

正如您所看到的,db1db2 是数据库的 2 个新实例,因此不一样,现在以这个例子为例。

$db1 = Database::Instance();
$db2 = Database::Instance();

以及 Instance 的代码

class Database
{
    private static $_instance;

    public static Instance()
    {
        if(self::$_instance !== null)
        {
            //We have already stored the object locally so just return it.
            //This is how the object always stays the same
            return self::$_instance;
        }
        return self::$_instance = new Database(); //Set the instance.
    }
}

如果您分析代码,您将发现无论您在应用程序中的哪个位置使用 Instance,您的对象都将始终相同。

静态函数是类/对象中的方法,是一种无需初始化对象即可使用的方法类型。

对于 __callStatic 方法,这是一个在静态方法不可用时执行的魔术方法。

例如:

class Database
{

    public static function first()
    {
        echo 'I actually exists and I am first';
    }

    public function __callStatic($name,$args)
    {
        echo 'I am '. $name .' and I was called with ' . count($args) . ' args';
    }
}

让我们测试一下它们。

Database::first(); //Output: I actually exists and I am first

Database::second(); //Output: I am second and I was called with 0 args

Database::StackOverflow(true,false); //Output: I am StackOverflow and I was called with 2 args

希望这对您有帮助

A single ton is a static function that allows you to keep track of your object instances, when you use a singleton you create an instance of the object but the instances always stays with the associated object.

Take this example:

$db1 = new Database();
$db2 = new Database();

as you can see that db1 and db2 are 2 new instances of Database therefore there not the same, now take this example.

$db1 = Database::Instance();
$db2 = Database::Instance();

And the code for Instance

class Database
{
    private static $_instance;

    public static Instance()
    {
        if(self::$_instance !== null)
        {
            //We have already stored the object locally so just return it.
            //This is how the object always stays the same
            return self::$_instance;
        }
        return self::$_instance = new Database(); //Set the instance.
    }
}

If you analyse the code you will so that no matter where you use Instance throughout your application your object will always be the same.

a static function is a method within a class/object isa type of method that can be used without the object being initialized.

In regards to __callStatic method, this is a Magic Method that's executed where a static method is not available.

For example:

class Database
{

    public static function first()
    {
        echo 'I actually exists and I am first';
    }

    public function __callStatic($name,$args)
    {
        echo 'I am '. $name .' and I was called with ' . count($args) . ' args';
    }
}

lets test them.

Database::first(); //Output: I actually exists and I am first

Database::second(); //Output: I am second and I was called with 0 args

Database::StackOverflow(true,false); //Output: I am StackOverflow and I was called with 2 args

Hope this helps you

终难愈 2024-09-25 20:16:06

单例是一种确保一次只有一个自身实例处于活动状态的对象。也就是说,每个程序只能创建一个,如果您明白我的意思的话。

静态方法是一种可以像普通函数一样在对象上下文之外调用的方法。就像 SomeClass:afunc() 而不仅仅是 $this->afunc()

A singleton is an object that ensures that only one instance of itself is active at a time. That is, you can only make one per program, if you know what I mean.

A static method is one that can be called like a normal function, outside of object context. Like SomeClass:afunc() and not only $this->afunc().

苯莒 2024-09-25 20:16:06

Singleton 意味着,您的此类只有一个与之关联的对象。因此,此类只会实例化一次,之后您将调用一个名为 getInstance() 的方法来返回您的实例。

静态,意味着要访问您不需要的方法属性以及该对象的实例,您可以直接使用其调用该方法 class class::myMethod()

__callStatic 是访问这些静态方法的方式。是 PHP magic-methods 之一,与 __call 类似,但有我刚才提到的区别。

对于最后一个问题,该类仅获得一个与数据库的连接。如果您添加另一个方法,例如,executeSelect($sql),您将得到如下内容:

public static function executeSelect($sql)
{
  if (self::$link)
  {
          self::getLink()
  } 
      // execute your query here...
  return null;
}

您只需要像这样调用它:Database::executeSelect($sql); 并且它永远不会同时获得两个到DB的连接。

Singleton means, that you have this class that will only have one object associated to it. So, this class will be only instantiated one single time, after that you will call a method with a name like getInstance() that will return your instance.

Static, means that to access that method or property you don't need and instance of that object, you can call that method directly with its class class::myMethod()

__callStatic is the way you access those static method. Is one of PHP magic-methods and is similar to __call with the difference I've just mentioned.

For the last question, That class only gets one connection to the database. If you add another method for example, executeSelect($sql) you will have something like:

public static function executeSelect($sql)
{
  if (self::$link)
  {
          self::getLink()
  } 
      // execute your query here...
  return null;
}

You will only need to call it like: Database::executeSelect($sql); and it will never get two connection to the DB simultaneously.

吾家有女初长成 2024-09-25 20:16:06
<?php 
class DB {
protected static $instance;
protected function __construct() {
if(empty(self::$instance)) {
        try {
            self::$instance = new PDO("mysql:host=localhost;dbname=techprojects", 'root', '');
            self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
        } catch(PDOException $error) {
            echo $error->getMessage();
        }
    }

}
public static function getInstance() {
    if(empty(self::$instance)) {
        try {
            new DB();
            //var_dump(self::$instance);
        } catch(PDOException $error) {
            echo $error->getMessage();
        }
    }
    //var_dump(self::$instance);
    return self::$instance;
}

private function __clone() {
    // Stopping Clonning of Object
}

private function __wakeup() {
    // Stopping unserialize of object
}
}
?>
<?php
try {
$db = DB::getInstance();
$db1 = DB::getInstance();
$sqlExample = 'SELECT * FROM keywords';
$stm = $db->prepare($sqlExample);
$stm->execute();
$result = $stm->fetchAll(PDO::FETCH_ASSOC);

var_dump($db);
var_dump($db1);
echo "<pre>";
print_r($result);
echo "</pre>";

} catch (Exception $e) {
print $e->getMessage();

}
 ?>
<?php 
class DB {
protected static $instance;
protected function __construct() {
if(empty(self::$instance)) {
        try {
            self::$instance = new PDO("mysql:host=localhost;dbname=techprojects", 'root', '');
            self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
        } catch(PDOException $error) {
            echo $error->getMessage();
        }
    }

}
public static function getInstance() {
    if(empty(self::$instance)) {
        try {
            new DB();
            //var_dump(self::$instance);
        } catch(PDOException $error) {
            echo $error->getMessage();
        }
    }
    //var_dump(self::$instance);
    return self::$instance;
}

private function __clone() {
    // Stopping Clonning of Object
}

private function __wakeup() {
    // Stopping unserialize of object
}
}
?>
<?php
try {
$db = DB::getInstance();
$db1 = DB::getInstance();
$sqlExample = 'SELECT * FROM keywords';
$stm = $db->prepare($sqlExample);
$stm->execute();
$result = $stm->fetchAll(PDO::FETCH_ASSOC);

var_dump($db);
var_dump($db1);
echo "<pre>";
print_r($result);
echo "</pre>";

} catch (Exception $e) {
print $e->getMessage();

}
 ?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文