I was wondering if this is an 'unwholesome' use of a factory pattern, or if it is completely reasonable:
<?php //ConnectionFactory.class.php
/**
* Generates prepared mysqli connection instances
*/
class ConnectionFactory {
public static function make(){
$c = new mysqli('localhost', 'testusername', 'fakepassword');
if ($c->connect_error) throw new ConnectionException("Connection failed");
return $c;
}
}
class ConnectionException extends Exception {}
?>
Or would an extension of the mysqli class with pre-populated arguments be more appropriate? I had thought about doing this, but it felt like violating the 'purity' of the mysqli class. Maybe I'm thinking too much into it.
My usage comes from having many classes which make database transactions. In all of the examples I have seen the username/password/host/etc have been re-written on each usage, which doesn't seem very OOP-like either.
It's worth noting that I would really prefer to use a Singleton, and this strikes me as the perfect opportunity for such (only one connection is ever needed which would be a huge performance boost as I understand it) but I'm trying to avoid the temptation because I hear that they are considered OOP cancer.
Perhaps the problem is that I shouldn't be using the mysqli class in so many places and maybe use a class with static 'do query' functions or something similar. All thoughts on the subject are greatly appriciated
You are over analyzing the problem. If you can't decide on the perfect implementation of a database connection you'll never get anything done.
This may be a case where a singleton makes sense, as making sure only one connection is open per-process is much more important than esoteric OOP guidelines.
Sounds like you are considering writing a thin db abstraction, and while I think that might be a little better than your code working with the mysqli object directly, you should be aware that this is well worn territory. If you really want to be database agnostic don't reinvent the wheel... just use PDO or some other DB abstraction or mapping tool.
While having a mysqli proxy object instead of direct mysqli interaction won't actually achieve db agnosticism it does have other benefits. Custom query logging, SQL sanity checking, sharding logic, and a number of other things could live in your thin db wrapper down the road. I say write your proxy object and instantiate it in some static variable or singleton somewhere and call it good. The OOP nazis can continue debating its perfection while you're moving on to more important things.