The generic CMS module
The generic module is mostly a stub. It only contains a few necessary functions and must be extended by the real class. There are a few things ANY module must be able to do:
-
It must accept and be able to store an array of parameters we include
-
It has a
fetch() function that returns the XHTML
-
It has an
optional init() function
-
It must be able to receive and store a reference to a Smarty object (for future)
As you might notice these requirements can actually be seen the requirements of an interface in the object oriented world. We will, however write a root class that we extend to real modules. Please notice that if you override the init() function in your own module you must call the parent::init() function to make sure you have a database handle if you need one. On the other hand if you do not need a database connection in your module you can override the init() in it using a dummy empty function.
This is a good starting point and includes the creation of Smarty instances that we will need later. A lot of other functionality is there as well and we do not need to rewrite it in every module. Save this file as modules/CmsModule.class.php
This module must be included in the application one way or another. A nice way of doing this is in Apache is create an ".htaccess" file in the web root directory and adding the following lines to it (the second line being the mandatory Registry class):
php_value auto_prepend_file path_to/CmsModule.class.php
php_value auto_prepend_file path_to/Registry.class.php
Now the module class file is included every time a browser visits the site. This makes sense at least during this tutorial. You can omit this advice and use standard includes, of course. In Windows (using Wamp) the first line might be:
php_value auto_prepend_file c:\wamp\mycms\lib\CmsModule.class.php
For nginx please go look at our nginx settings page.
Our first real-life module
Now we will write an utterly simple module that simply
-
reads the contents of an HTML file (or any text file)
-
outputs its contents (or returns it to the main template).
This is not as stupid as it may sound as sometimes there is really a need for something as simple as this. Let’s assume we call the module like this:
{cmsmodule name="html" file="html/under_construction.html"}
The cmsmodule definition has two parameters: name and file. The name parameter instructs our plugin to load the correct class file. The file parameter is saved into the module's intance so that it knows which file to display. This is simple! We are overriding the init() using and empty function because we do not need to check the database connection (which is what the parent::init() would have done):
So the plugin must load the class above and feed the instance so that it has the correct file name on its $vars['file'] slot.