php


PHP OOP Database Class - Is it really needed? [closed]


I'm currently learning to code using OOP in PHP and have quite often come across database classes and abstraction layers. I'm coding a CMS as a big challenge and I started to code a database class without thinking about it too much.
I'm actually leaning towards using MySQLi as is (I think it's pretty good to use as is), rather than creating a class to deal with CRUD operations so do I really need a class to deal with all that stuff?
If not, what would be the best way of going about connecting to a database, just do it at the start of my application and pass the connection around? Or is there really a huge benefit of coding a database class that I'm missing?
I'm thinking that error handling would be one such benefit but if I'm keeping my class as close to MySQLi as possible, is that a good enough reason to go ahead with a class?
Thank you for the good question.
PHP OOP Database Class - Is it really needed?
Definitely yes, but only if you don't like screenfuls of repetitive code for the every query executed in your code.
If you take a fresh look at the code you need to perform one average query, you may notice that it's amount just horrible. While all you need is to just define a query, pass variables, run it and get results, you have to write thousands of useless operators, repeated for the every query.
An example right from the manual (even without error handling)
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
$stmt->bind_param("s", $city);
$stmt->execute();
$stmt->bind_result($district);
$stmt->fetch();
echo $district;
}
An example of using a database helper class:
$district = $db->getOne("SELECT District FROM City WHERE Name=?s", $city);
echo $district;
and that's for the single row only. For the array of rows the amount of code will be doubled in case of using raw API
In case of using mysqli things gets even worse.
Let's take simple example. Imagine there is a array of ids of unknown size. You need to add them all tho IN statement in the simple query
SELECT * FROM t WHERE id IN (1,2,3) // filled from array.
Try to get your data using mysqli prepared statements
The main benefit is that if you can get all your code to go through your database objects. You can easily change the database implementation in the future. You say you are learning towards mysqli but say half way down the line you changed to PDO, you would have to refactor -everything-.
Using your custom database objects, you can simply alter the integration without effecting the rest of the code. E.g. Your objects->connect() function could still be called exactly as it is right now but the underlying code would change and as it was all within your custom class, the changes you make are minimal.
This is just one of many benefits. A custom class that interfaces with the database object to run queries and store results are quite common to see (the model part of an MVC - usually extending a common base object often called a RecordSet or similar that has functions to run select/update/delete/etc). As again, you can easily change the implementation from one method to another.
What I've described is a pretty common advantage for Object Orientated Programming in general. Please see Your Common Sense's answer for another good advantage.

Related Links

How to create JSON with PHP array?
send File and Data in Ajax
cannot save to audit error table - Yii2 Audit
Laravel 5 how to return previous view without including the most recent $_GET parameters
stof_doctrine_extensions can't load in symfony
Change colour in html using php
PHP session not working after upgrading
PHP random_int(0,63) : Cannot open source device
Saving a array on a column Text Type
Improving MongoDB Aggregation Pipeline Performance
Zen Cart - if this is checkout page
How to Get Subcategories by category name in wordpress?
Access Token in PHP? [duplicate]
How to fix php_intl.dll issue in Ampps?
Fish codility excercise
Php trying to get property of-non-object

Categories

HOME
protocol-buffers
memory
verification
freeradius
cucumber
long-integer
activex
foaf
nsview
docker-cloud
google-webmaster-tools
amp
elk-stack
material-components
mosquitto
angular-meteor
wagtail
reportviewer
siesta
lda
scrape
match
cqrs
mailmerge
multi-step
ex
sql-injection
heap-dump
phonegap-build
google-tasks-api
c#-7.0
user-defined-types
playframework-2.0
cocos2d-android
google-sites
office-ui-fabric
cpu-usage
clr
spring-shell
opam
data-type-conversion
unity-container
device
substring
quartz.net
data-collection
high-availability
webviewclient
uri
running-object-table
points
math.js
nic
source-insight
toad
progid
fotorama
microsoft-certifications
ms-media-foundation
numerics
netstat
assertions
jslint
code-rally
nanogallery
cloudera-quickstart-vm
microsoft-ui-automation
best-buy-api
grails-spring-security
classnotfoundexception
fiware-wirecloud
flume-twitter
gcal
windows-media-player
image-registration
lightning-workbench
renderman
front-camera
perl-data-structures
haraka
bigdecimal
wininet
raw-sockets
exists
flush
textpattern
ruby-on-rails-4.1
astropy
canopy
algebraixlib
relational-model
phpredis
ssmtp
mutators
mod-auth-openidc
juttle
jquery-mobile-flipswitch
ecos
bittorrent-sync
tabletools
django-settings
insertonsubmit
codahale-metrics
disjoint-union
insertion
sunstudio
system-requirements
zend-pdf
android-dialog
workflow-manager-1.x
msinfo32
uipasteboard
page-curl
mongrel2
formal-semantics
aptitude
ccl
pinax
resharper-5.0
main-method
tacit-programming
fuzzy-comparison
accumulator
isapi-redirect
service-factory

Resources

Encrypt Message