The next step that I’m going to take regarding the development of the previous “AbstractModel” class will consist of implementing the “__set()” and “__get()” magic functions provided by PHP 5. These methods will be used to dynamically create properties for the class without having to declare them before, and for retrieving their assigned values as well. In reality, the use of property and method overloading in PHP 5 has been a controversial topic, but in this case I’m going to use it as a shorthand for handling properties of the “AbstractModel” class. Now it’s time to pay attention to the implementation of these methods, which looks like this: // Sets a new property for the model function __set($property, $value) { if(in_array($property, array_merge($this->fields, array('error', 'result')), TRUE)) { $this->$property = $value; } }
// Gets the value of an existing property of the model function __get($property) { if(isset($this->$property)) { return $this->$property; } return NULL; }
Quite simple to follow, right? As you can see, the previous “__set()” and “__get()” methods have been implemented in a pretty classical way. Speaking more specifically, the first method is responsible for creating only properties that have the name of the database table associated with the model class, with the exception of a couple called “error” and “result.” These last two will be used by the class later on to store errors and result sets respectively. The “__get()” method will return to client code the value of a specified property and nothing else. It’s that simple, really. At this point, the previous class starts to look a bit more functional, since now it’s capable of associating a specific database table with a given model. It also has the ability to assign and retrieve properties on the fly via the property overloading. So, what’s the next step? Well, in the last section I’m going to add two other methods to the class, which will be tasked with selecting and inserting database records. However, the most interesting aspect of this process will be that one of these methods will be chainable as well. To see how this will be done, click on the link below and read the following segment.
blog comments powered by Disqus |
|
|
|
|
|
|
|