MySQLi类模式的连接,关闭,离开? [英] MySQLi class pattern for connection, close, leave open?

查看:244
本文介绍了MySQLi类模式的连接,关闭,离开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如果创建一个类如下所示是一个好的做法。



所以我每次都使用self :: $ mysqli对象我需要做一些工作,连接只会关闭__desctruct()。另外,扩展类仍然只保留一个连接,因为$ mysqli被声明为静态的。



这种方式我只有一个连接认为脚本

  class db {
protected static $ mysqli;

function __contruct(){
$ this-> mysqli = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_DATABASE);
// DB_HOST,DB_USER,DB_PASS,DB_DATABASE在别处定义
}

function __destruct(){
$ this-> mysqli-> close
}
}

我想知道您对此的看法。 / p>

解决方案


我想知道如果创建类似下面的类是一个好的做法。


我认为这不是好的做法。这是特别的一个原因:你描述为什么你认为你需要它的问题:每个请求只有一个连接。



你不需要编码任何东西。 mysqli 有一个很好的功能内置,默认连接。每次创建一个新实例时,它会从ini设置(配置)中选择数据库连接参数:

  $ db = new mysqli ; 

由于所有的数据库连接在脚本完成时关闭,所以根本没有太多关注。你唯一需要做的是实例化连接一次,并将变量传递给所有需要 mysqli 对象的代码。



另一种不良做法是您要引入

$

c> class MysqliSingleton extends mysqli
{
private static $ instance;
/ **
* @return MysqliSingleton
* /
public function getInstance()
{
if(NULL === self :: $ instance )
self :: $ instance = new self();
return self :: $ instance;
}
private function __construct()
{
}
public function __clone()
{
throw new RuntimeException允许。
}
public function __wakeup()
{
throw new RuntimeException('Unserializing is not allowed。
}
}

它的工作方式如下:

  $ mysqli = MysqliSingleton :: getInstance(); 

并且总是返回一个mysqli实例,这可能是你正在寻找的。但是单身人士被认为有害,因为他们可能带来很多问题,请参阅相关问题谁需要单身人士?



您可以更容易地创建一个包含数据库实例的变量。你可以另外封装一些延迟加载,以防你的应用程序不总是需要一个mysqli连接,例如。有一个非常简单的上下文类:

  interface ContextMysqli 
{
/ **
* @return mysqli
* /
public function getMysqli();
}

类上下文实现ContextMysqli
{
private $ mysqli;
public function getMysqli()
{
$ this-> mysqli || $ this-> mysqli = new mysqli();
return $ this-> mysqli;
}
}

脚本启动时,只需实例化上下文并传递它到你需要它的代码的每一部分:

  $ context = new Context 
...
$ result = do_some_db_work($ context);
...
function do_some_db_work(ContextMysqli $ context)
{
$ mysqli = $ context-> getMysqli
...
}

这个建议可能有点短视,但它比一个单例,而不是引入很多东西。好处是你已经封装了逻辑,当创建 mysqli 对象时需要一个单例。您的代码现在独立于全局或静态上下文。


I would like to know if creating a class like the one below would be a good practice.

So I would use the self::$mysqli object every time I need to do some work and the connection would only get closed on __desctruct(). Plus, extending the class would still maintain only one connection since $mysqli is declared static.

this way I would have only one connection thought the script

class db {
 protected static $mysqli;

 function __contruct(){
  $this->mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DATABASE);
  // DB_HOST, DB_USER, DB_PASS, DB_DATABASE defined elsewhere
 }

 function __destruct(){
  $this->mysqli->close();
 }
}

I would like to know your insights about this.

解决方案

I would like to know if creating a class like the one below would be a good practice.

I would consider it not to be good practice. That's especially for one reason: the problem you describe why you think you need it: Only one connection per request.

You don't need to code anything. mysqli has a nice feature build in, the default connection. It picks the database connection parameters from the ini settings (configuration) each time you create a new instance:

$db = new mysqli;

As all database connections get closed when the script finishes, there is not much to care about at all. The only thing you need to do is to instantiate the connection once and pass the variable around to all code that needs that mysqli object.

Another bad practice is that you're introducing a Singleton Doc here, something like:

class MysqliSingleton extends mysqli
{
    private static $instance;
    /**
     * @return MysqliSingleton
     */
    public function getInstance()
    {
        if (NULL === self::$instance)
            self::$instance = new self();
        return self::$instance;
    }
    private function __construct()
    {
    }
    public function __clone()
    {
         throw new RuntimeException('Clone is not allowed.');
    }
    public function __wakeup()
    {
        throw new RuntimeException('Unserializing is not allowed.');
    }
}

It would work like this:

$mysqli = MysqliSingleton::getInstance();

and would always return that one mysqli instance, which might be what you're looking for. However Singletons are considered harmful as they can introduce a lot of problems see the related question Who needs singletons?.

It's easier you create yourself a variable that you pass around containing the database instance. You can additionally encapsulate some sort of lazy-loading in case your application does not always need a mysqli connection, e.g. with a very simple context class:

interface ContextMysqli
{
    /**
     * @return mysqli
     */
    public function getMysqli();
}

class Context implements ContextMysqli
{
    private $mysqli;
    public function getMysqli()
    {
        $this->mysqli || $this->mysqli = new mysqli();
        return $this->mysqli;
    }
}

When your scripts start, just instantiate your context and pass it to every part of your code where you need it:

$context = new Context();
...
$result = do_some_db_work($context);
...
function do_some_db_work(ContextMysqli $context)
{
    $mysqli = $context->getMysqli();
    ...
}

This suggestion might be a little shortsighted as well, but it's better than a singleton while not introducing much ado. The benefit is that you have encapsulated the logic when to create the mysqli object w/o the need of a singleton. Your code is now independent to global or static context.

这篇关于MySQLi类模式的连接,关闭,离开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆