PHP:数据库连接类构造方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9937953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:56:45  来源:igfitidea点击:

PHP: Database Connection Class Constructor Method

phpoopclassdatabase-connection

提问by Aaron

I'm new to OOP. Originally I was defining variables and assigning values to them within the class and outside of the constructor, but after an OOP lesson in Java today, I was told this is bad style and should be avoided.

我是 OOP 的新手。最初我是在类内和构造函数外定义变量并为它们赋值,但今天在 Java 的 OOP 课程之后,我被告知这是一种糟糕的风格,应该避免。

Here is my original PHP database connection class that I mocked-up:

这是我模拟的原始 PHP 数据库连接类:

class DatabaseConnection {
    private $dbHost = "localhost";
    private $dbUser = "root";
    private $dbPass = "";
    private $dbName = "test";

    function __construct() {    
        $connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass)
            or die("Could not connect to the database:<br />" . mysql_error());
        mysql_select_db($this->dbName, $connection) 
            or die("Database error:<br />" . mysql_error());
    }
}

Is the above considered okay? Or is the following a better way?

以上认为可以吗?或者以下是更好的方法?

class DatabaseConnection {
    private $dbHost;
    private $dbUser;
    private $dbPass;
    private $dbName;

    function __construct() {
        $this->dbHost = "localhost";
        $this->dbUser = "root";
        $this->dbPass = "";
        $this->dbName = "test";

        $connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass)
            or die("Could not connect to the database:<br />" . mysql_error());
        mysql_select_db($this->dbName, $connection) 
            or die("Database error:<br />" . mysql_error());
    }
}

What should I be focusing on to make sure I am understanding OOP correctly?

我应该关注什么以确保我正确理解 OOP?

回答by tere?ko

First of all: this is pointless.

首先:这是没有意义的。

You are creating an object wrapper for the 10+ year old mysql_*function. This php extension is no longer maintained and the process of deprecation has already begun. You should not use this API for any new projects in 2012.

您正在为 10 多年的mysql_*函数创建对象包装器。这个 php 扩展不再维护,弃用过程已经开始。2012 年,您不应将此 API 用于任何新项目。

Instead you should learn how to use PDOor MySQLiand work with prepared statements.

相反,您应该学习如何使用PDOMySQLi并使用准备好的语句

That said .. lets take a look at your code:

也就是说..让我们看看你的代码:

  • Constructor should receive all the parameters required for creating new instance, parameters should not be hard-coded in the class definition. What if you need to work with two databases at the same time ?
  • When connection is created, it should be stored in object's scope variable. Something along the lines of $this->connection = mysql_conn.... Instead you store it in local variable, which you "loose"right after constructor is done.
  • You should not use privatevariables for everything. They are not visible to classes which would extend your original class. Unless it is intentional, you should choose protectedfor this.
  • The or die('..')bit most go. Do not stop the whole application if connection fails. Instead you should throw an exception, which then can be handled outside of the constructor.
  • 构造函数应接收创建新实例所需的所有参数,不应在类定义中硬编码参数。如果您需要同时使用两个数据库怎么办?
  • 创建连接时,它应该存储在对象的作用域变量中。类似的东西$this->connection = mysql_conn...。相反,您将它存储在局部变量中,在构造函数完成后立即“松开”
  • 你不应该private对所有事情都使用变量。它们对于将扩展您的原始类的类不可见。除非是故意的,否则你应该选择protected这个。
  • or die('..')最去的 位。如果连接失败,不要停止整个应用程序。相反,您应该抛出一个异常,然后可以在构造函数之外处理它。

回答by Matthew Blancarte

Well, it's not going to run quite yet. You need to change your variables so that they match your connection params:

嗯,它还不会运行。您需要更改变量以使其与您的连接参数匹配:

$dbHost = "localhost";

Should be

应该

$this->dbHost = 'localhost';

I normally don't put my login params inside of the class at all. I would pass them into the constructor when the object is created. Use an outside config file so you can actually use this class on more than one build. :)

我通常根本不会将我的登录参数放在课程中。创建对象时,我会将它们传递给构造函数。使用外部配置文件,以便您可以在多个构建中实际使用此类。:)

Update::

更新::

Okay, so here are a few little OOP configuration gold-nuggets that help you build a dynamic Database class.

好的,这里有一些小的 OOP 配置金块,可帮助您构建动态数据库类。

  • Check out http://redbeanphp.com/It will allow you to do a psuedo ORM style of data modelling. Super easy to install, and ridiculously easy to get your database up and running. http://redbeanphp.com/manual/installing

  • Create a configuration file that contains things like constants, template setups, common functions, and an AUTOLOADERConfiguration files are key when working in version controlled environments. :)

  • Build your Database class as an abstract class http://php.net/manual/en/language.oop5.abstract.php

    abstract class Database
    {
      public function update()
      {
      }
    
      public function deactivate()
      {
      }
    
      public function destroy()
      {
      }
    
      //etc.
    }
    
    class MyAppObject extends Database
    {
    }
    
  • Put all of your class files into a library folder, and then put your configuration file into that library. Now, to make your life easier you can use an autoloader function to bring your classes to life whenever you need them, without having to include any specific class. See below:

    //note: this is never explicitly instantiated
    //note: name your files like this: MyAppObject.class.php  
    function my_fancypants_autoloader( $my_class_name )
    {
      if( preg_match( "%^_(Model_)%", $my_class_name ) ) return;
      require_once( "$my_class_name.class.php" );
    }
    spl_autoload_register( 'my_fancypants_autoloader' );
    
    • Now all you have to do is include one configuration file in your .php files to access your classes.
  • 查看http://redbeanphp.com/它将允许您进行数据建模的伪 ORM 风格。超级容易安装,并且让您的数据库启动和运行非常容易。http://redbeanphp.com/manual/installing

  • 创建一个配置文件,其中包含常量、模板设置、常用功能和AUTOLOADER配置文件是在版本控制环境中工作时的关键。:)

  • 将您的数据库类构建为抽象类http://php.net/manual/en/language.oop5.abstract.php

    abstract class Database
    {
      public function update()
      {
      }
    
      public function deactivate()
      {
      }
    
      public function destroy()
      {
      }
    
      //etc.
    }
    
    class MyAppObject extends Database
    {
    }
    
  • 将所有类文件放入库文件夹,然后将配置文件放入该库。现在,为了让您的生活更轻松,您可以使用自动加载器功能在您需要时随时将类变为现实,而无需包含任何特定类。见下文:

    //note: this is never explicitly instantiated
    //note: name your files like this: MyAppObject.class.php  
    function my_fancypants_autoloader( $my_class_name )
    {
      if( preg_match( "%^_(Model_)%", $my_class_name ) ) return;
      require_once( "$my_class_name.class.php" );
    }
    spl_autoload_register( 'my_fancypants_autoloader' );
    
    • 现在你要做的就是在你的 .php 文件中包含一个配置文件来访问你的类。

Hope that points you in the right direction! Good luck!

希望这能指出你正确的方向!祝你好运!

回答by Daniel Quinn

The latter is probably better, but with an adjustment: pass some arguments to the constructor, namely the connection info.

后者可能更好,但有一个调整:将一些参数传递给构造函数,即连接信息。

Your first example is only useful if you've got one database connection and only if you're happy hard-coding the connection values (you shouldn't be). The second example, if you add say, a $nameparameter as an argument, could be used to connect to multiple databases:

您的第一个示例仅在您有一个数据库连接并且您乐于对连接值进行硬编码时才有用(您不应该这样做)。第二个例子,如果你添加一个$name参数作为参数,可以用来连接到多个数据库:

I'm new to OOP. Originally I was defining variables and assigning values to them within the class and outside of the constructor, but after an OOP lesson in Java today, I was told this is bad style and should be avoided.

我是 OOP 的新手。最初我是在类内和构造函数外定义变量并为它们赋值,但今天在 Java 的 OOP 课程之后,我被告知这是一种糟糕的风格,应该避免。

class DatabaseConnection {
    private $dbHost;
    private $dbUser;
    private $dbPass;
    private $dbName;

    function __construct($config) {
        // Process the config file and dump the variables into $config
        $this->dbHost = $config['host'];
        $this->dbName = $config['name'];
        $this->dbUser = $config['user'];
        $this->dbPass = $config['pass'];

        $connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass)
            or die("Could not connect to the database:<br />" . mysql_error());
        mysql_select_db($this->dbName, $connection) 
            or die("Database error:<br />" . mysql_error());
    }
}

So using this style, you now have a more useful class.

所以使用这种风格,你现在有一个更有用的类。

回答by JT Smith

Here is mine and it works rather well:

这是我的,效果很好:

class Database
{
   private static $_dbUser = 'user';
   private static $_dbPass = 'pwd';
   private static $_dbDB = 'dbname';
   private static $_dbHost = 'localhost';
   private static $_connection = NULL;

   /**
    * Constructor
    * prevents new Object creation
    */

   private function __construct(){
   }

   /**
    * Get Database connection
    * 
    * @return Mysqli
    */

   public static function getConnection() {
      if (!self::$_connection) {
     self::$_connection = @new mysqli(self::$_dbHost, self::$_dbUser, self::$_dbPass, self::$_dbDB);

         if (self::$_connection -> connect_error) {
            die('Connect Error: ' . self::$_connection->connect_error);
         }
      }
      return self::$_connection;
   }
}

By making the __constructempty, it prevents a new class being instantiated from anywhere. Then, make the function static so now all I need to do to get my connection is Database::getConnection()And this is all in an includefile, in a password protected folder on the server and just included with each class file. This will also check to see if a connection is already open before attempting another one. If one is already established, it passes the open connection to the method.

通过__construct清空,它可以防止从任何地方实例化新类。然后,将函数设为静态,所以现在我需要做的就是获得连接Database::getConnection(),这一切都在一个include文件中,在服务器上受密码保护的文件夹中,并且只包含在每个类文件中。这还将在尝试另一个连接之前检查连接是否已经打开。如果已经建立,它将打开的连接传递给该方法。

回答by greut

Since your are only using them into the __constructmethod, you don't need them as class attributes. Only the $connectionhas to be kept for later use imho.

由于您只在__construct方法中使用它们,因此您不需要它们作为类属性。$connection恕我直言,只有必须保留以备后用。

It might be much much better to not give any default values to those arguments but let them being set from the outside.

最好不要为这些参数提供任何默认值,而是让它们从外部设置。

$db = new DatabaseConnection("localhost", "user", "password", "db");

They are plenty of PHP tools for that already, find them, read them and learn from that. First of all, use PDOand what is true in Java isn't always true in PHP.

它们已经有大量的 PHP 工具,可以找到它们,阅读它们并从中学习。首先,使用PDO并且在 Java 中正确的内容在 PHP 中并不总是正确的。

回答by khandla vijay

<?php

    class config
    {
        private $host='localhost';
        private $username='root';
        private $password='';
        private $dbname='khandla';

        function __construct()
        {   
            if(mysql_connect($this->host,$this->username,$this->password))
            {
                echo "connection successfully";
            }
        }
        function db()
        {
            mysql_select_db($this->$dbname);
        }
    }

    $obj=new config();
?>