To be frank, I am quite new to object oriented programming. I’m more familiar with procedural code such as C and so forth.
I started designing a website with php as its underlying framework. Originally, I stuck with a procedural style design. That became quite cumbersome rather quickly. Needless to say, I want to use an object oriented approach. I see many opportunities to do so.
One in particular is in terms of accessing a database – MySQL in this case.
Right now, I am deciding how I want to design a database class. Obviously, it will incorporate a connection through PHP’s PDO. But I am stuck on what to include in the class other than that. It can clearly contain other methods, but to what degree? For instance, should I also include functions for MySQL querying, inserts, deletions, etc? These are common functions I’ll need to call regularly, so shouldn’t I include them all within the same class? Otherwise, it seems almost pointless to use classes if I need to create four or more different ones?
Anyone with more experience, please help! Thanks!
I like the idea of writing your own simple wrapper class. If at some point in the future you will want to switch to a different db library then all you have to do is change the code in the wrapper class.
Where I work we wrote a wrapper class for php mysql functions. We have production and testing server where main mysql server is located on production and also additional server with replication. Our wrapper figures out where to connect to pull the data – there are cases where it connects to replicant for selects only. Credentials to every database we may want to connect to is defined in the wrapper which simplifies usage. Class methods are to execute sql, fetch one or all rows and dump into array, escape data, return last id etc. There is also a method that appends comment to each SQL statement with some useful information (like the file where query was executed) to ease debugging.
Example to get data into array:
and later on in the same code we can issue update or insert using the same instance.