I have noticed an interesting technique Doctrine is using for for it's Connection and Statement interfaces.
They have a class called PDOConnection, which naturally extends PDO, but also implements Connection, an interface created by Doctrine.
The Connection interface defines copies of several PDO methods, and although Doctrines PDOConnection class doesn't implement all of them, the fact it extends PDO means it does.
My best guess why they did that is they wanted to design their connection drivers around PDO's methodology, but what I really what to know is what this pattern is called and if it regularly gets used.
My best guess why they did that is they wanted to design their connection drivers around PDO's methodology
Yep, that's it. There is no special pattern for this.
Related
My web project has a class called DB_CONNECTOR where all the functions are bundled that interact with the mysql database. These would be functions like get_user(), add_user(), change_user_attribute() and many more. In each of these functions a sql query is executed and as is good practice, I use prepared statements (with named parameters).
Currently the connection to the database is established in the constructor of the class and also all the statements are prepared there. I thought this would be a good idea, so the statements are all immediatly ready for execution.
Now I realized that my use case is often to create a db_connector object, execute one or maybe two functions and then the objects lifecycle ends and at a later step a new one might be constructed (or not). So, I'm not so sure anymore if it smart to put the prepared statements in the constructor as it is forseeable that I will end up with at least 20 or likely more prepared statements.
So my question is:
is it a good idea to prepare all the statements in the constructor even if only one or two are used?
Or should I prepare them in the functions right before execution to avoid stressing the db with unneeded preparations?
This answer is based in both my experience and humble opinion, but I'll try to elaborate my arguments so it isn't just some random guy's opinion.
I don't think the database connection must be the core object in your application, let alone the only one. It'd expect to see an entirely different class for the user, so you can later have further classes for everything else. Otherwise, your application will eventually consist of a single class in a 5000 line file and your class will not be suitable to track entity data at instance level and you'll need to pass variables around in method calls. That's pretty much procedural code in OOP dress.
Also, I don't that making your User class inherits from Database (something pretty frequent nonetheless) is practical at all. Interlacing the database connection and the business logic objects doesn't really simplify application design and actually makes some parts harder.
The design of the database layer itself is pretty much standardised:
One connection per application (or more... you may need to connect to several sources!)
One statement per query.
This is exactly how PDO works.
Given that, it's easier to make the database classes just one more dependency of your entities rather than their grandparent. The injection of this dependency can be done by different means:
Make it a class property:
public function __construct(\PDO $connection)
{
$this->connection = $connection;
}
Pass it to the methods they actually needed (if not many of them):
public function getOrders(\PDO $connection)
{
$stmt = $connection->prepare('SELECT ...');
}
... or use one of those fancy dependency injection containers you can find at Packagist.
Be aware that there're also object-relational mapping (ORM), active record pattern... Those are entirely different families of solutions which may suit your needs or not depending on your use case, but not what I'm describing here.
Said that, it becomes obvious that you prepare the statements at the exact point where you need them. This design doesn't even allow otherwise ;-)
I'm implementing a database class to open connection, read, write, delete, update, etc. I'm currently using MySql server.
I'm attempting to write a database class that will be able to cater for different database in future. Maybe we will switch to SQL Server in future. because of this, I hope to design my class in such a way that I can write new classes for SQL Server and it wouldn't affect the client/controller that is calling the database class. I would like to stick to the design pattern principle, open for extension, closed for modification.
In strategy, I could create a abstract class, and create multiple concrete classes for MySql or SQL Server? Does anyone know which pattern should I follow that doesn't violate the rules for these patterns? I am not too sure about adapter. I read that adapter is used to interface existing classes. But in my case, I will be creating my new db classes for SQL Server. Unless I'm using an opensource class.
I'm trying to make a small cms in php and mysql, and want it to be object-oriented
I have a class DbConnector that handles all sql queries. Then I have some other classes that needs to alter the database through the DbConnector.
As I see i I have to either send the DbConnector instance as a parameter in every class initialization, or I can make a new DbConnector instance for each class, which to me seems pretty unnecessary.
What is the preferred way to do this or is it all wrong?
The preferred way of doing this would be Dependency Injection, the lazy / easy / OK for small scale way could be a Singleton database object.
All,
I have a PHP application written in Zend Framework with MVC style. I plan to use Zend_DB to connect to the MySQL database and process queries. I am looking for a wrapper class which makes it easy to use Zend_DB class. This wrapper class will have a constructor that connects to the Mysql db using Zend_DB. It will also have a method to return a singleton instance for each and every db connection made.
Something like:
$pptDB = PPTDB::getInstance();
$pptDB->setFetchMode(PPTDB::FETCH_OBJ);
$result = $pptDB->fetchRow('SELECT * FROM bugs WHERE bug_id = 2');
echo $result->bug_description;
Where class PPTDB extends Zend_DB
Is this something feasible to have? If not, how ls would you use Zend_DB in a major application?
Thanks,
AFAIK it is possible to use Zend_DB as a standalone (well, all classes in that package should also be available of course), but if you're not using the models there is little to gain from is. If you're only interested in the database abstraction I'd recommend PDO, if you want a Zend_DB wrapper Reflection can give you a nice list of properties / functions you can choose to override or not.
http://nl2.php.net/reflection
You should create adapter using Zend_Db::factory() and than use it in Zend_Db_Table_Abstract::setDefaultAdapter(). Then you can get your adapter wherever you want using Zend_Db_Table::getDefaultAdapter() or $table->getAdapter() :)
I am looking for an example of a simple, but functional example of a class extending the mySQLi class in PHP5. I am interested in stored procedures also. Basically what I need is an example of a practical and usable class. I learn best by example and unfortunately I have been unable to find any site or book that seems to have a really solid yet simple example. All the examples I see are way to complicated so I am unable to understand or they are so simple that I might as well just instantiate the class right then and there inline. It would be great if somebody could supply me with an example like this and explain whats going on however well they can. My long term goal is to have a class that I can instantiate that deals with authentication of the database and then takes my SQL statements and supplies the output in variables.
If anyone is willing to take the time to help me out it would be much appreciated!
,Thanks
Did you check PHP PEAR MDB2 ?
http://pear.php.net/package/MDB2
Its not so simple, its the best DAL in php IMHO...
About mysqli, you can take a look at those articles :
ext/mysqli: Part I - Overview and Prepared Statements
Using ext/mysqli: Part II - Extending mysqli
(Quite old, but mysqli extension has not changed that much for a couple of years, so those should still be OK)
You could also have a look at PDO, included in PHP since version 5.1 ; it's an object-oriented API to access multiple DB engines (you don't use mysqli_query, pg_query, oci8_query or stuff like that ; only $pdo->query -- well, your SQL has to be compatible, but that's another problem ;-( )
Another approach would be using an ORM, like, for instance, Doctrine.
It's not a class that extends MySQLi, but a full Framework to abstract the DB engine - with that, you write a schema to describe you DB's structure, and you then use a "pseudo-SQL" language to send queries ; or just (for most cases) the object-oriented API that abstracts SQL.
It's a bit difficult to use, at first, but really powerful and useful (and not bad for productivity, I think, for many kind of projects)
give a try to DALMP: http://code.google.com/p/dalmp/ is support prepared statements and many cache backends
Little bit off topic but why MySQLi? PDO is much better and considered a defacto PHP standard these days. I wrote a simple PDO class a year or two ago, I can give you link if interested.
Here is a simple example of adding built in query timing to the mysqli class.
This assumes you have defined a "MyTimer" class implementing the iTimer interface. iTimer class, in it's simplest form, would record the start and stop times for the specified $key (using microtime() or getrusage() or whatever).
<?php
interface iTimer
{
public function start($key);
public function stop($key);
}
class mysqlp extends mysqli
{
function query($query, $resultmode)
{
$timer = MyTimer::getInstance();
$timer->start('mysqli::query');
$result = parent::query($query, $resultmode);
$timer->stop('mysqli::query');
return $result;
}
}
#usage
$mysqli = new mysqlp("localhost", "my_user", "my_password", "world");
$results = $mysqli->query("SELECT id FROM foo");