douye5949
douye5949
2014-03-20 17:29

ALL的一个连接,OOP PHP

已采纳

struggling to grip the varying levels of variables in OOP PHP. I want to have one connection file which can be accessed from all classes and functions through out my project. I include 'config.php' but the $mysql variable cannot be found. Any help greatly appreciated;

I have a file

config.php

public $mysqli = new mysqli('localhost', 'usernameEG', 'passwordEG', 'databaseEG');

if (mysqli_connect_errno()) {
    printf("Connect failed: %s
", mysqli_connect_error());
    exit();
    }

and a few class files

class.User.php

<?php

class User {

private $mysqli = null;

function __construct(){

    //=========
//include config.php  here?
    }

function myProfile($Id){

$stmt = $this->mysqli->prepare("SELECT First_Name, Last_Name, Email, DateJoined FROM members WHERE Id = ? ");
$stmt->bind_param('i',$Id);
$stmt->execute();
$stmt->bind_result($fname,$lname,$email,$date);
$stmt->store_result();
$stmt->fetch();

        echo "<p>User#: ".$Id."</p>";
        echo "<p>First Name: ".$fname."</p>";
        echo "<p>Last Name: ".$lname."</p>";
        echo "<p>Email: ".$email."</p>";
        echo "<p>Date Joined: ".$date."</p>";
        $stmt->close();

}
function example(){
EXAMPLE CODE HERE WILL ALSO NEED TO BE ABLE TO USE SAME CONNECTION
}

}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongrou5254 dongrou5254 7年前

    So rather than a singleton approach as hinted at in the other answer. Let me offer you a dependency injection approach. For a lot of experienced developers, dependency injection is a preferred approach, as it allows the class receiving the dependency to have looser coupling to the dependency (for example, you don't need to even know the name of the class for instantiating the dependency like you would with a singleton approach). You just need to know that the dependency being passed meets some interface requirement (i.e. it implements some interface or is a certain type of class).

    So that would look more like this:

    class User {
        protected $mysqli = null;
    
        // other properties
    
        public function __construct(mysqli $mysqli) {
            $this->mysqli = $mysqli;
            // other constructor operations
        }
    
        // other methods
    }
    

    So what is happening here? Here you enforce the requirement to pass an object of type mysqli when instantiating this class. This could be a mysqli object or perhaps even your own custom class which extends mysqli, the User class doesn't care, so long as all mysqli class methods are implemented

    Usage could be like

    require('/path/to/db_config.php'); // an include which creates a mysqli object or provides a factory for one, or whatever
    $user = new User($mysqli);
    $user->foo(); // do something
    

    Interestingly enough, you might at times see use of singelton pattern along with dependency injection. So say you had a mysqli_singleton_factory class with singleton functionality to provide you the single instantiated mysqli object. The usage might look like this:

    require('/path/to/db_config.php'); // an include which provides a singleton
    $user = new User(mysqli_singleton_factory::get_instance());
    $user->foo(); // do something
    $other_class = new other_class_requiring_mysqli(mysqli_singleton_factory::get_instance());
    $other_class->bar(); // do something
    

    Here you have both guaranteed that you only have one instantiated mysqli object during script execution AND you have decoupled your User class from having to do any instantiation of the object itself.

    For reference, a singleton pattern may look like this:

    class mysqli_singleton_factory {
        protected static $mysqli = null;
    
        protected function __construct() {
            // assume DB connection setting have been pre-defined as constants somewhere
            $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
            // make sure connection worked
            if($mysqli->connect_error) {
                throw new Exception(__METHOD__ . ' at line ' . __LINE__ . ' failed with: ' . $mysqli->connect_error);
            }
            self::mysqli = $mysqli;
        }
    
        public static function get_instance() {
            if (false === self::mysqli instanceof mysqli) {
                self::__construct();
            }
            return self::mysqli;
        }
    }
    
    点赞 评论 复制链接分享
  • douyun6781 douyun6781 7年前

    I've done this a number of times previously and I have found that it is easy to implement "singleton-like" class to serve as a database connector which then can be referenced by any object in the application.

    config.php

    Config.php is where the credentials are set and the database class is actually constructed.

    $dbHost = 'localhost';
    $dbUser = 'someUser';
    $dbPass = 'somePass';
    $dbSchema = 'someSchema';
    Database::$db = new MySQLi($dbHost, $dbUser, $dbPass, $dbSchema);
    

    classes.php

    classes.php is where my classes are defined, which is kept separate from the rest of the code.

    class Database {
        public static $db;
    }
    
    class User {
      ...
      function example()
      {
         $stmt = Database::$db->prepare('SELECT TRUE');
         ...
      }
    }
    

    index.php

    index.php is the entry point for the app, and is used to handle the request and exhibit the desired behavior using the supplied classes.

    require_once('classes.php');
    require_once('config.php');
    /* Application Goes Here */
    

    This ensures that all objects in my project use the same connection, I only have to invoke it once and I don't have to mess about with scope too much.

    点赞 评论 复制链接分享

相关推荐