Skip to content

How to create a plugin for RainTPL 3

rainphp edited this page Jan 17, 2013 · 1 revision

RainTPL 3 loads plugins which are basically scripts executed on filters (or hook).

A simple example of plugin it could be an image remover, probably un-useful in real life, but really handy to explain how plugins work.

  1. we create the file library/Rain/Tpl/plugins/RemoveImages.php
   <?php
   // set the namespace
   namespace Rain\Tpl\Plugin;
   // require the Plugin class
   require_once __DIR__ . '/../Plugin.php';

   class RemoveImages extends \Rain\Tpl\Plugin
   {
        // hooks
	protected $hooks = array('beforeParse');

        // text that replace the image
        protected $replacement = "[IMAGE REPLACED]";

        /** 
        * Function called by the filter beforeParse
        **/
	public function beforeParse(\ArrayAccess $context){
		// get the html
		$html = $context->code;

		// remove the image and set the $context->code
                $context->code = preg_replace( '#<img.*?>#', self::$replacement, $html );

	}

        /**
        * Change the replacement word
        **/
        public static function setWord($word){
            self::$replacement = $word;
        }

}
  1. Now we're ready to include the plugin in the RainTPL, so here's the code to prepare the plugin:
        <?php
        use Rain\Tpl;

    	// Add ImageReplace plugin
	require_once "library/Rain/Tpl/Plugin/PathReplace.php";
	Tpl::registerPlugin( new Tpl\Plugin\ImageReplace() );
  1. A plugin can also have properties and methods, in our example we can call setWord() to change the replacement word for the image:
    Tpl\Plugin\ImageReplace::setWord( "IMAGE CENSORED" );

Filters

Plugins can be executed on specific filter (or hook), so here is the filters list:

  • beforeParse, executed at the beginning of Tpl::compileTemplate(), right before any parsing operation
  • afterParse, executed at the end of Tpl::compilerTemplate(), after the parsing operation and before returning the parsed code.

More filters will be added soon in the class.

Default Plugins

RainTPL ship already with few useful plugins:

  • PathReplace, it replace the relative path of images, link, stylesheet, scripts and input with the correct path on the server. You can set the tag you want to replace, you can also configure the base_url of your application with Tpl::configure("base_url", $url );
  • ImageResize, is an handy plugins that resize the image into the templates with the size indicated in the width and height attribute, you can set quality and crop of the image from the code.

If you work on a plugin please share it with us, we'll soon create a section to share/download more plugins!