Reputation: 81
Hello i'm using php and i'm trying to make a database class where the constructor will connect the class to the database and assign the pointer to a class variable. The problem that I have is that every time a new instance of the class is created, the constructor gets called and the code connects to the database. I don't see why it should connect to the database every single time that it is called so how would i go about make a class variable that's the same in all the instances and once it is given the pointer, it won't create it again.
Thanks
Upvotes: 1
Views: 141
Reputation: 58444
Instead of making new connection for each class you create, you should create a single connection an share it between the classes.
$connection = new PDO( ... );
$first = new Foo( $connection );
$second = new Bar( $connection );
In this way both instances have access to the same connection.
You also might benefit from watching this video: The Clean Code Talks - Don't Look For Things!
Upvotes: 0
Reputation: 29925
Hi you have two options.
Your best bet is creating a singleton class. This is a class which references itself so that you can never create more than one of it. If you try to create more than one of it it will return the currently initialised version of itself.
Otherwise stick with what you have and just make sure you're not calling new
every time.
e.g.
$db = new Database(); // call this once to create
// don't do this again
$anotherdb = new Database();
// just use the db object from before
$db->query("...");
However this might get confusing, and you might lose scope of the variable, so I would suggest going with the singleton method. Some people will tell you not to use singleton's but its up to you. Works well with database classes.
If you look around on the internet you will find examples of other database classes to look at.
Have a look at frameworks like codeigniter too, they use their own database classes. It might be worth looking at how they work.
Upvotes: 2
Reputation: 174947
Database connection shouldn't go in the constructor. You should have a ConnectionFactory
class, which would connect do the database and return a new DatabaseConnection
object.
<?php
class ConnectionFactory {
public static function newConnection($credentials) {
//Connect to database
$connection = new PDO(/* Credentials */);
return $connection;
}
}
$connection = ConnectionFactory::newConnection(CREDENTIALS);
Upvotes: 2