In my project I have a database class that I use to handle all the MySQL stuff. It connects to a database, runs queries, catches errors and closes the connection.
Now I need to create a members area on my site, and I was going to build a users class that would handle registration, logging in, password/username changes/resets and logging out. In this users class I need to use MySQL for obvious reasons... which is what my database class was made for.
But I'm confused as to how I would use my database class in my users class. Would I want to create a new database object for my user class and then have it close whenever a method in that class is finished? Or do I somehow make a 'global' database class that can be used throughout my entire script (if this is the case I need help with that, no idea what to do there.)
Thanks for any feedback you can give me.
Since you are using the database as an object, why not just add methods to the object that your "users class" can employ to take care of the things it needs to do. The users class can contain a pointer to the database class. The database class will protect your database, and assure that the users class is using it appropriately.
Here is a solution using PDO.
As he said, put all your functions in the database class and use the database object to access those functions from your user class. This should be the best method in your case. Eg:
global $database;
userclassvar = $database->doSomething();
I think the better aproach would be to create the database class that instatiate right away on its own on a database.php and then include it on user.php. then every time you create a function that needs a database, you globalise the database object.
Check this. databse.php
here is the user.php
What I like to do is make the database class with the Singleton pattern in mind. That way, if you already have a database object, it just retrieves it, otherwise creates a new one. For example:
And now you can use
User
's$_link
property to do the database functions, like$this->_link->query(...)
. You don't necessarily have to put theDb::getLink()
in the constructor if your class doesn't have to interact with the database that much.Simple, 3 step process. 1/ Create a database object. 2/ Give it to your user class constructor. 3/ Use it in the user methods.
Little example.
File Database.class.php :
In User.class.php :
Now, in userManager.php for example :
If you want the current trendy name of this old technique, google "Dependency Injection". The Singleton pattern in php will fade away soon.