Sefam
Sefam

Reputation: 1773

Classes using mysqli

I am building an API in PHP and I have a question. I'm using classes, and some of these classes need to access my database. However, I don't want to define variables for the database in every single class in order to open it, or have to send my mysqli object as a parameter of every single class constructor.

What would be the best way to go about this? Do I define a global variable of some kind?

Upvotes: 0

Views: 255

Answers (3)

Your Common Sense
Your Common Sense

Reputation: 157839

A classic solution would be as follows

  1. Create an instance of dbatabase handler class, either raw mysqli (worse) or better abstraction class (way better)
  2. In the constructor of your application class take this db class instance as a parameter and assign it to a local variable
  3. Use this variable with your class.

A quick example:

class Foo()
{
    protected $db;
    function __construct($db);
    {
        $this->db = $db;
    }
    function getBar($id)
    {
        return $this->db->getOne("SELECT * FROM bar WHERE id=?i", $id);
    }
}
$db = new safeMysql();
$foo = new Foo($db);
$bar = $foo->getBar($_GET['id']);

Upvotes: 3

ChicagoRedSox
ChicagoRedSox

Reputation: 638

In a system I maintain my app needs to access its own MySQL db, as well as remote Oracle and SQL Server databases, and I use a trait for it. Here's a simplification of my code, just using MySQL:

dbaccess.php

trait DatabaseAccess {
    protected $db;
    private $host = 'host', $dbName = 'db', $username = 'username', $password = 'pword';

    public function connectToMysql() {
         $this->db= new mysqli(......);
    }
}

then in myclass.php

require 'dbaccess.php'; 
class MyClass {
    use DatabaseAccess;

    //class code.....
}

All elements of DatabaseAccess will be available as if you hand-typed them in MyClass. Note: if you're using PHP < 5.4, then this solution won't be possible.

Upvotes: 0

Aaron Gong
Aaron Gong

Reputation: 1005

How about using a static classes?

class mysqli_wrapper {
private static $db = null;

public static function open() {
    GLOBAL $opts; // this can be global or setup in other ways
    if (!self::$db) {
        self::close();
        self::$db = null;
    }
    self::$db = @mysqli_connect('p:'.$opts['hn'], $opts['un'], $opts['pw'], $opts['db']);
    return self::$db;
}
public static function query($qry) {
    return mysqli_query ( self::$db, $qry );
}
public static function affected_rows() { return @mysqli_affected_rows(self::$db); }
public static function error() { return @mysqli_error(self::$db); }
public static function close() { @mysqli_close(self::$db); }
} // end mysqli_wrapper

mysqli_wrapper::open(); //  Here's how to call it

Upvotes: 0

Related Questions