You seem to be in a similar situation as I was a few years ago.
I knew how OOP worked in theory, had seen all the classic examples (class Dog extends Animal, etc), but had no idea how to actually put that into something useful.
What really opened my eyes was the concept of a Record class that corresponds to a row in a database table. I'd worked with databases quite a lot and my code was always an unorganized mess of basic SELECT/INSERT/UPDATE queries that was hard to maintain and only partially safe against SQL injections.
With a Record class, it might go something like this:
Assume you've got a table called testTable with multiple columns including id and quantity.
// Creates the object, runs a 'SELECT * from testTable WHERE id = 123' query
// and stores the returned row in an array inside the object
$record = new Record('testTable', 123);
// Let's say the quantity column was 3 where id was 123.
// This would set $quantity to 3.
$quantity = $record->getField('quantity');
$newQuantity = $quantity + 1;
$record->setField('quantity', $newQuantity);
// Runs an 'UPDATE testTable SET quantity = 4 WHERE id = 123' query
$record->save();
And then possible improvements to consider:
- Make the ID parameter in the constructor optional. If ID is not provided, it would skip the SELECT query and do an INSERT query in save() later on.
- Add an isNew() method which returns true if the row doesn't exist in the database yet.
- Add a getID() method which would start returning the inserted ID after save() has been run.
- If you haven't already, do all SQL injection safety checking inside the Record class so you'd never have to worry about it when using the class.
- Make the Record class implement ArrayAccess, so that instead of
$quantity = $record->getField('quantity');
and
$record->setField('quantity', $newQuantity);
you could do
$quantity = $record['quantity'];
and
$record['quantity'] = $newQuantity;
- Extend the record class as TestTableRecord:
- Override the constructor to only require the ID parameter and pass the 'testTable' to the parent version (ex:
parent::__construct('testTable', $id);
)
- Add an increaseQuantity() method to the extended class.
Some may want to point out that similar classes already exist in common PHP OOP frameworks and you shouldn't need to reinvent it. But for learning purposes, I'd highly recommend going through the process at least once. Otherwise it can be very difficult to understand those frameworks at first.