The Smarty Plug-in
We are writing our CMS module as a Smarty plug-in. Before going any further we will define how our module system works. As you have already noticed from the classes we wrote previously we have made one big decision:
Instead of writing dozens of Smarty plug-ins for our CMS tasks we will write a generic plug-in that loads the "working class object" using some parameters, initiates an instance and calls its fetch() method.
What this means is that we will have a loader that must
- find the real class definition path,
- load the class code,
- create an instance of it and
- apply the variables we have declared in the module definition
- call the instance's fetch() method
Naming conventions
This is a very important phase because we will build the rest of the system on a few assumptions. The most important of them is the name of the module. In this tutorial we use the
<modulename>_module.php convention. If, for instance, when creating the module "html" the class file must be "html_module.php". We must also be able provide full path to the module file. We assume that the root module directory is modules (relative to the application path) and all modules are in their own directories under it. So the "html" module path is "modules/html/html_module.php". This is not a law so you may choose your own directory structure - provided you know what you are doing. Please note that we will have the option to keep several modules in one directory.
If you have your Smarty directory ready to be used you can write the plugin.
function.cmsmodule.php
... wait a moment...
Okay, this should do the trick. Save this file to the Smarty plugins directory and name it "
function.cmsmodule.php".
Now let us do a simple test. Remember the
html module we just wrote? We want that module to output an HTML file called info.html which is located in the "html" directory. We load the plug-in in the template:
{cmsmodule name="html" filename="html/info.html"}
The templating engine core should load the plug-in function we have just written. The parameter filename will end up in the plugin and (by Smarty class magic) from there to our CmsModule derived instance of html_module.
Now you can follow the chain of events in the plug-in code above. After creating an instance of html_module the plug-in calls its setParams() and init() functions and when creating the object adds the parameters information to the vars[] array in the module. Finally it calls the fetch() function which returns the contents of the html file. The Smarty instance then outputs the contents to where the plugin was defined. Zero echo statements needed, Sir!
Now it is time to test what we have achieved so far (not much but exciting!)