I’ve been wanting to mess around with some of the new features in PHP 5.3, so I took the opportunity to write a base model class that can be used for simple db based models. This isn’t really production type code, more of an example of “look what php can do now”, although with some error handling and tweaking, it might be a good start to a lightweight active record type base class.
One of the biggest new changes to 5.3 is late static binding. It has never been possible in PHP to get the name of the calling class when you called a static method inherited from a parent. Now with late static binding, this is possible. This is what works the “magic” in this base class.
The Assumptions
Models represent an entity stored in the database (think active record):
- In one table per class named the same as the model class, but all lower case
- With one column for each property
- With a primary key column named ‘id’
In addition, a global variable $db should contain a PHP PDO object.
The Base Class
One of the things I’d like to be able to do is create an object from an array of parameters, whether they come from a database or not. I might want to create from a set of parameters and be able to act on it immediately, without having to reload it. I use reflection here to ensure that all the class properties are set, throwing an exception if any are missing.
Note also in the get and getAll methods, the calls to new static(). What this does is create an object of the class you are calling, rather than the class that the method exists in. This wasn’t possible until PHP 5.3, and is really the key to being able to use static inheritance.
In addition, there is a lambda function in the save method, this is new to 5.3 also. And there are a few examples of a new php function “get_called_class()” which will return the name of the class that was called.
Source
http://www.zacharyfox.com/blog/php/simple-model-crud-with-php-5-3