Writing an Extension
It is incredibly simple to write your own extension. This will walk you through the basic process, by recreating the included extension for JSON encoding and decoding.
If you'd like to share your own extensions, please let me know on the CodeIgniter forum. Eventually, I'd like to start building a repository of extensions.
Planning an Extension
An extension is simply a class with one or more exposed methods. These methods have a few minor rules.
- Extension methods must be public.
- They can not start with an underscore (_).
- They will not overwrite a DataMapper method, or a previously loaded extension's method.
You can include private methods simply by prepending the method with an underscore (_). These methods will not be exposed in the DataMapper model, but will be available for your use.
Creating the Extension Class
The class is a normal PHP class. The file should follow the same naming rules as a CodeIgniter Library, naming the file the lowercase form of the class name, ending with .php. Store the class definition in the application/datamapper.
application/datamapper/json.php
<?php class Json { } /* End of file json.php */ /* Location: ./application/datamapper/json.php */
Adding a Public Method
We want to be able to easily convert a DataMapper model into a JSON object. We'll use PHP5's json_encode for the heavy lifting, but we need to get the data out of the large and complex DataMapper model first.
The first argument to each public method is always the $object in use.
Adding a Public Method
<?php class Json { function to_json($object) { $fields = $object->fields; $result = array(); foreach($fields as $f) { $result[$f] = $object->{$f}; } $json = json_encode($result); if($result === FALSE) { return FALSE; } return $json; } } /* End of file json.php */ /* Location: ./application/datamapper/json.php */
Now we can call $object->to_json(), and we'll get a JSON encoded view of $object.
To learn more, take a look a the included extensions.