Using php constants and static functions directly in smarty template of Symfony2

0.00 avg. rating (0% score) - 0 votes
The Symfony Framework is well-known for being really flexible and is used to build micro-sites, enterprise applications that handle billions of connections and even as the basis for other frameworks. Some time back we started using Symfony2 for our new projects. Symfony2 comes with twig as the default templating engine but we chose to use smarty as the templating engine using the SmartyBundle of Symfony2.
Smarty is great, but for maintainability reasons, they have deprecated the possibility of adding php tags in the template. This means we will not be able to use php class constants & static functions directly in our template files. This was a huge drawback. Though the same can be achieved using plugins, writing plugins for every constant or static function is not a great idea. Smarty still allows us to use global constants easily in the templates as shown below
e.g: <?php
        // the constant defined in php
        define(‘MY_CONST_VAL’,’BluePrint’);
        ?>


       Use the constant in a smarty template as
       {$smarty.const.MY_CONST_VAL}
But for abstraction and logic separation we need cases where we have to define constants and static methods in different php classes. We needed to figure out a way to use these constants and static methods directly in smarty template files. We knew that smarty has a way to register classes, so we decided to solve our problem using the same capability of smarty. Below are the steps to use php class constants in smarty while using Symfony2.
Before starting the steps description, let me remind you, one of the best practices when developing a Symfony2 application is to make it configurable via use of “parameters.yml” file. It contains information such as the database name, the mailer hostname, and custom configuration parameters.
               
Step 1:
First of all we will have to add information about the classes, in “parameters.yml” file, the classes from which we need to use static functions as well as constants. Below is the example and description of the same.
e.g:    – in parameters.yml of your application add the following
           smarty.overrides:
               register.classes:
                   MyClass1: EducationHubMyBundleResourcesmodelMyClass1
                   MyClass2: EducationHubMyBundleResourcesmodelMyClass2
                                   …
Step 2:
               
We need to make a custom smarty engine class extending “SmartyEngine” and add the code to register all the classes given in parameters.yml, the method given below can be used as an example:
    class MyProjectSmartyEngine extends SmartyEngine {
             ………
             ………
         public function __construct(Smarty $smarty, ContainerInterface $container,
         TemplateNameParserInterface $parser, LoaderInterface $loader, array $options,
         GlobalVariables $globals = null, LoggerInterface $logger = null){
                  ……..
                  ……
           }
 
          private function enrichSmartyHandle(Smarty $smarty, ContainerInterface $container)
      {
       try
       {
           $classes = $container->getParameter(“smarty.overrides”); //This will get the value of “smarty.overrides” param from yml file.
           foreach ($classes[“register.classes”] as $name=>$path)
           {
               try
               {
                   $smarty->registerClass($name, $path);
               }
               catch (Exception $e){
                  //Exception Message
               }
           }
       }
       catch (Exception $e){
           //Exception Message
       }
    }
  
Step 3:
Now we have to make symfony use our custom MyProjectSmartyEngine class instead of the default SmartyEngine Class. This can be done by using the “Compiler pass” capability of Symfony2.
This can be done as under:  
– Create a compiler pass class
class SmartyCompilerPass implements CompilerPassInterface{
    public function process(ContainerBuilder $container) {
       if (!$container->hasDefinition(‘templating.engine.smarty’)) {
           return;
       }
       $smartyDef = $container->getDefinition(‘templating.engine.smarty’);
       $smartyDef->setClass(“<MyBundlePath><path to MyProjectSmartyEngine>”);
    }
}
– add the compiler pass in your bundle php file <MyBundle>.php
class <MyBundle> extends Bundle{
public function build(ContainerBuilder $container)
    {
       parent::build($container);
……
……
       $container->addCompilerPass(new SmartyCompilerPass());
    }
}
Step 4:

Now your tpl files  are ready to use all of the registered class constants as well as static methods declared beneath those classes. 
 
Points To Remember:
We can only use those classes which have been declared in our “parameters.yml” file.
Usage : {MyClass1::myConstant} or {MyClass1::myStaticMethod($arg)}

One thought on “Using php constants and static functions directly in smarty template of Symfony2

Comments are closed.