Hey there,
We all love arrays, and we all use them all the time, especially in PHP world filling up an empty associative array with data is one of the most mundane tasks.
I must say due to the convenience of it and the habit I was on the same train for quite some time.
There is nothing wrong with arrays, besides the fact that they can get slow, and I mean slow on big objects as well as get really slow when you are filling them up with data.
I am going to share an idea that is kinda ORM and ActiveRecord related, but in the same time I feel flexible enough to let me write SQL queries freely.
/** * Basic Data Representation * Represents the db table structure. */ class dataModel { //set the properties that match the DB table you are representing protected $id; protected $first_name; protected $last_name; // implement setter and getters // add logic if you want to public function __set( $key, $value ) { if ( ) { ... } } } /** * The actual model * Extends the representation layer and makes operations * **/ class myModel extends dataModel { public function __construct() { $sSQL = " ....my sql ... "; while( <db_fetched_data> ) { $this->id = $myresult->id; } ... more code ... } $oModel = new myModel(); echo $oModel->id;
Ok , here is what this does – you have a basic class that represents your table via it’s properties, and an actual class that extends it and makes the SQL calls.
For the purposes of the example – it will load the values of course every time you instantiate it via it’s constructor, but of course it doesn’t have to be this way.
The loading and instancing can be implemented with singleton pattern in mind, or whatever else needs you might have.
On one hand we have the data we are working on represented in a object and on the other hand we are skipping the “extra” layer that the actual ORM libraries add. I am not claiming that this is better or worse than ORM, but rather a different take on it.
Cons:
– harder to maintain
– working with related tables things can get messy ( this is where ORM is better ) .
– when altering the table , one must alter the representation class as well
Pros:
– really , really fast – no key seek while filling up arrays, no nothing.
– smart data manipulation on “load” time – meaning logic can be implemented on setters and getters
– no extra layer of logic just to issue queries
– really flexible to be modeled per your needs – no ties with a framework
– setters can explicitly define what data can be loaded into the object
I have managed to shave off about 0.5MB memory usage when I implemented this into my projects, but I would love to hear from fellow developers if anybody is willing to give it a shot.
-Evgeni