Please be brutally honest, and tear my work apart if you have to.
So I'm re-writing a small web application that I recently made. The reason for this is simply that the code got pretty messy and I want to learn and apply better OO design. What this application should do is just simple CRUD.
I have a database with 3 tables, companies
and partners
which are in no relation to each other, and city
which has a 1:n relation with companies and partners. Very simple, really. Now, I have several questions which I will state at the end of my post. Here I'll just try to explain:
My first approach was that I created classes company, partner, and city, fetched all datasets from the database, and created objects from that:
class company {
private $id = null;
private $name = null;
private $city = null;
//many more attributes
function __construct( $id, $name, $city, [...] ) {
$this->id = $id;
$this->name = $name;
$this->city = $city;
//huge constructor
}
/*
* getters + setters here
*
* no need to paste the partner class as it looks just like this one
*
*/
}
And that is all these classes did. I fetched every dataset from the database and constructed company, partner, and city objects (the attribute city within these classes is an object with several attributes itself) and saved them into two arrays arr_companies
and arr_partners
, which then held these objects...and it worked fine like that.
Now, what I wanted is to update, insert, delete into the database, and all 3 classes (city, company, partner) need this functionality. My approach was that I created a new class with a constructor that would basically take 2 strings command and object, e.g. ('update', 'company')
and it would then update the company directly in the database leaving my objects untouched. That made me really sad because I had such nicely constructed objects and I didn't know how to make use of them.
Questions:
Is it bad to have such huge constructors (my biggest one would take 28 parameters)?
Should you have a separate class for database operations or is it better to have maybe an abstract class or interface for it and let the subclasses themselves handle update, delete, and insert?
Is it common to just write, and delete from the database whenever, or should I just apply these changes to my objects and only execute the commands to the database later, for example when the session ends?
I figure an application like this must have been done a fantastillion times before. What is the proper approach here? create objects, work with objects, and save them to the database?
I have so many questions but I think many of them I just don't know how to ask.
Please note that if possible I would not like to use an ORM at this point.
Thank you very much for your time.