I want to be able to make classes which extend the MySQLi class to perform all its SQL queries.
$mysql = new mysqli('localhost', 'root', 'password', 'database') or die('error connecting to the database');
I dont know how to do this without globalising the $mysql object to use in my other methods or classes.
class Blog {
public function comment() {
global $mysql;
//rest here
}
}
Any help would be appreciated.
Thanks.
You can use PHP's extends keyword just for any other class:
or better use object aggregation instead of inheritance:
My suggestion is to create a Singleton DataAccess class, instantiate that class in a global config file and call it in your Blog class like
$query = DataAccess::query("SELECT * FROM blog WHERE id = ".$id)
.Look into the Singleton pattern, it's a pretty easy to understand designpattern. Perfect for this situation.
Your DataAccess class can have several methods like
query
,fetchAssoc
,numRows
,checkUniqueValue
,transactionStart
,transactionCommit
,transactionRollback
etc etc. Those function could also be setup as an Interface which gets implemented by the DataAccess class. That way you can easily extend your DataAccess class for multiple database management systems.The above pretty much describes my DataAccess model.
My standard method is to make a singleton class that acts as the database accessor, and a base class that everything requiring such access inherits from.
So:
Have a look at PDO, which throw exceptions for you to catch if a query fails. It's widely used and tested so you shouldn't have a problem finding existing solutions whilst using it.
To inject it into your blog class:
I was working on something similar. I'm happy about this singleton class that encapsulates the database login.
To use you can have something like this: