Recently, I have done several projects using the Database Object superclass, which I use to quickly query / update records and expand with the corresponding classes, such as the User class.
I found that many classes that I wrote have the same methods: query_values โโ(), update (), delete (), etc.
So, I came up with a constructor class that looks like this:
public function __construct($table, $db_object, $record_id = null){ $this->db = $db_object; // Database object with query methods $this->table = $table; // The name of the database table $this->get_column_data(); if(!is_null($record_id)){ // This retrieves all column values, // stores into private $fields array property $this->query_values($record_id); } }
And the constructor of the child class is as follows:
public function __construct($db_object, $record_id = null){ parent::__construct($this->table, $db_object, $record_id); }
Where the $ table property is defined above, since we need to know which table this particular object is working with.
Now all the common methods of managing the record are in one place, and the methods specific to this class are all that is defined in their respective child classes.
The biggest drawback that I see here is that all data fields are extruded and encapsulated in the $ fields property, so you need to define common get and set methods (which I usually do), which almost negates encapsulation *, or the method should be defined specifically for each property that we want to expose.
* Example: $ user_id = $ User-> id; // DO NOT USE MY METHOD against $ user_id = $ User โ _ get ('id'); // ACCESSES $ User-> fields ['id']
Do you see this as a flaw, or a plus? The goal is ease of use, object orientation (encapsulation) and just awesome!