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 22805
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 (in Solutions
explorer)and attempt to add a...
|
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 written some test code and its almost syntax error...
|
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
Class1 *newitem = new Class1(param1, param2);
...
|
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 property in the ParentClass in the ChildClass? If the
|
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 class; as expected, but why do I have a 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
user clicks on the grid, say, the events occur on...
|
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 specific as
possible. My question has nothing to...
|
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 functions for writing specific data to the database.
...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
| |