Hi,
Im just learning OO in PHP and not sure the best method to use the functions for example in a database wrapper class within another class for example which handles all user authentication. I have put together this test code of how I am currently implementing it: - <?
-
class DB
-
{
-
public function __construct($host,$user,$pass,$dbname)
-
{
-
mysql_connect($host,$user,$pass)
-
or die(mysql_error());
-
mysql_select_db($dbname)
-
or die(mysql_error());
-
}
-
public function qry($sql)
-
{
-
return mysql_query($sql)
-
or die(mysql_error());
-
}
-
}
-
-
class User
-
{
-
public $user_id;
-
public function __construct($user_id)
-
{
-
$this->user_id = $user_id;
-
}
-
public function update_user()
-
{
-
global $db;
-
$db->qry(" UPDATE users SET active = 1
-
WHERE user_id = '" . $this->user_id . "' ");
-
}
-
}
-
-
$db = new DB("localhost","root","","test_database");
-
$user = new User(2);
-
-
$user->update_user();
-
?>
Is that use of global considered bad practice? I was browsing the source of PHPBB3 and they use the global method when accessing its database class from other classes however I believe I can instead pass a reference to the object via a param so would that method be better? If someone could give me a few pointers it would be appreciated.
Cheers.
8 22600
Have a database property for your User class. -
-
class DB {
-
-
// ...
-
-
}
-
-
class User {
-
-
private $_db;
-
-
public function User ( )
-
{
-
$this->_db = new DB;
-
}
-
-
}
Hi Markus,
Thanks for the response, however I do have a question.
The __construct() for the DB class opens the connection from the login parameters passed. Therefore with your method I need to have the login details hard coded into the USER class itself rather than in the code which creates the instances.
Is this the standard practice for using classes within classes? Can you see my problem and advise of a possible workaround?
Thanks.
a common practice for DB classes is implementing the Singleton pattern (which can also hold the DB access data (maybe coded through constants)
the User class doesn't need to pass DB data, unless you want to (be able to) connect to different databases.
Thanks Dormilich.
I checked out about the Singleton pattern, follows some tutorials and came up with this which works well in that it only calls the database connection once and I can use that class within any other classes, here is my example code: - <?
-
class DB
-
{
-
private static $dbInstance;
-
-
public function __construct($host,$user,$pass,$dbname)
-
{
-
echo("Would have connected to " . $host . " DB.<br />");
-
}
-
-
public static function getInstance($host=null,$user=null,
-
$pass=null,$dbname=null)
-
{
-
if (!self::$dbInstance)
-
{
-
self::$dbInstance = new DB($host,$user,$pass,$dbname);
-
}
-
return self::$dbInstance;
-
}
-
-
public function qry($sql)
-
{
-
echo("Would have executed: " . $sql . "<br />");
-
}
-
}
-
-
class User
-
{
-
private $db;
-
public function __construct()
-
{
-
$this->db = DB::getInstance();
-
}
-
public function SelectUsers()
-
{
-
$this->db->qry(" select * from users ");
-
}
-
}
-
-
class News
-
{
-
private $db;
-
public function __construct()
-
{
-
$this->db = DB::getInstance();
-
}
-
public function SelectNews()
-
{
-
$this->db->qry("select * from news");
-
}
-
}
-
-
$dbc = DB::getInstance("localhost", "root", "", "test_database");
-
$usr = new User();
-
$usr->SelectUsers();
-
$usr->SelectUsers();
-
$nws = new News();
-
$nws->SelectNews();
-
$usr->SelectUsers();
-
?>
This will produce the following output: - Would have connected to localhost DB.
-
Would have executed: select * from users
-
Would have executed: select * from users
-
Would have executed: select * from news
-
Would have executed: select * from users
So you can see it only connects once which is great and I dont need to provide DB login details within any of the classes.
Thanks for everyones help.
Cheers.
[EDIT] Unfortunately, you got the Singleton Pattern wrong. what about - $a = new DB(…);
-
$b = new DB(…);
?
you must leave the __construct() and __clone() methods empty in a Singleton pattern! (OK, you may throw an Exception or leave a note)
you can also try to pass the DB parameters via static properties. - require "db.config.php";
-
-
class DB
-
{
-
private static $dbInstance = NULL;
-
public static $host;
-
// or using a default value via constants
-
// public static $host = DB_DEFAULT_HOST;
-
public static $user;
-
public static $pass;
-
public static $dbname;
-
-
public function __construct() { }
-
-
public function __clone() { }
-
-
public static function getInstance()
-
{
-
if (self::$dbInstance === NULL)
-
{
-
self::$dbInstance = new self;
-
self::connect();
-
}
-
return self::$dbInstance;
-
}
-
-
private static function connect()
-
{
-
# do DB connection here
-
}
-
}
-
-
// optional if you use your defaults
-
DB::$host = "localhost";
-
DB::$user = "****";
-
DB::$pass = "****";
-
DB::$dbname = "my_db_name";
-
$dbc = DB::getInstance();
-
Dormilich, thanks for that clarification.
I have implemented what you desribed and its working fine.
Thank you.
I'm glad I could be of help.
OOP rulez. @Dormilich
incorrect, but I noticed that way too late.
just for additional information a Singleton like DB class using PDO - // used for connecting to MySQL
-
// stores the Prepared Statements
-
(the interface, so that all DB_User classes
-
can safely call the methods)
-
abstract class DB implements DB_connector
-
{
-
/* PDO instance */
-
private static $PDO = NULL;
-
-
/* collection of Prepared Statements */
-
private static $PS = array();
-
-
/* DB name to set up */
-
public static $dbname = DB_DEFAULT_NAME;
-
-
/* close DB connection on script end */
-
function __destruct()
-
{
-
self::$PDO = NULL;
-
}
-
-
/* create a single instance of PDO */
-
public static function connect()
-
{
-
if (self::$PDO === NULL)
-
{
-
try {
-
// server, login & password hardly ever change in a project
-
$dsn = 'mysql:host=' . DB_SERVER . ';dbname=' . self::$dbname;
-
self::$PDO = new PDO($dsn, DB_USER, DB_PASS);
-
}
-
catch (PDOException $pdo)
-
{
-
// any kind of error logging*
-
ErrorLog::logException($pdo);
-
-
// throw Exception so you can safely quit the script
-
$emsg = "MySQL connection failed.";
-
throw new ErrorException($emsg, 500, 0);
-
}
-
}
-
}
-
-
/* save the Prepared Statements. I prefer to have them where the
-
PDO object is. just personal preference */
-
public static function prepare($index, $sql)
-
{
-
# check if $index already exists (implement your own way)
-
-
self::connect();
-
-
try {
-
self::$PS[$index] = self::$PDO->prepare($sql);
-
}
-
catch (PDOException $pdo)
-
{
-
ErrorLog::logException($pdo);
-
return false;
-
}
-
return true;
-
}
-
-
/* since the Prepared Statements are private, a getter method */
-
public static function getStatement($index)
-
{
-
if (isset(self::$PS[$index]))
-
{
-
return self::$PS[$index];
-
}
-
-
// do some error handling here
-
}
-
}
-
-
* ErrorLog is an Abstract Registry Pattern class that collects caught
-
Exceptions (and is able to display them later)
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Dave |
last post by:
I have a Solution with two projects. I am trying to
reference a class in project2 from project1. When I
right click on the project1 references...
|
by: Guenther Sohler |
last post by:
This is probably very easy to answer but for me its new.
Yesterday I realized the need to be able to define a class within another
one. So I have...
|
by: uvts_cvs |
last post by:
template <class T>
class foo
{
public:
template <class Tin>
T bar (Tin) {return T();}
};
|
by: Stephen Corey |
last post by:
I've got 2 classes in 2 seperate header files, but within the same
namespace. If I use a line like:
// This code is inside Class2's header file...
|
by: Craig Buchanan |
last post by:
If I declare a class within another class like:
Class ParentClass
...
Class ChildClass
...
End Class
End Class
How do I reference a...
|
by: Billy |
last post by:
In .Net 2, when I have created a strongly typed dataset of a SQL table
and then 'viewed' the code from the RHM menu. I am taken to the new
partial...
|
by: Gman |
last post by:
Hi,
I have created a usercontrol, a grid control essentially. Within it I
have a class: clsGridRecord. I have coded the events such that when a...
|
by: Nick Valeontis |
last post by:
Hi to all!
I am writing an implentation of the a-star algorithm in c#. My message is
going to be a little bit long, but this is in order to be as...
|
by: nathj |
last post by:
Hi,
I have a data abstraction class that holds all the functions for query the database.
I now have a second class that holds all the...
|
by: Kemmylinns12 |
last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
|
by: jalbright99669 |
last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
|
by: antdb |
last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine
In the overall architecture, a new "hyper-convergence" concept was...
|
by: Matthew3360 |
last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function.
Here is my code.
...
|
by: AndyPSV |
last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...
|
by: Oralloy |
last post by:
Hello Folks,
I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA.
My problem (spelled failure) is with the...
|
by: Carina712 |
last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand....
|
by: BLUEPANDA |
last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS...
|
by: Rahul1995seven |
last post by:
Introduction:
In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python...
| |