Using volt compiler as an external Component

Hey, i'm working on integration of Volt for a website that uses really old php coding type, but this is not the problem. The problem is while i'm using the compiler. Let's look at my example :

<?php
$compiler = new \Phalcon\Mvc\View\Engine\Volt\Compiler();

            $compiler->setOptions(array(
                "compiledPath" => __DIR__.'/views_compiled/',
                "compiledSeparator" => "%%"
            ));

            try{

                $VALUE_I_WANT_TO_KNOW = "path_to/my_compiled_file.volt.php";

                if( file_exists($VALUE_I_WANT_TO_KNOW)  || time() - filemtime($VALUE_I_WANT_TO_KNOW) > 3600 ){
                    $baseCwd=getcwd();
                    // chdir for include/extend while compilition runs
                    chdir(__DIR__."/views");
                    $compiler->compile($templateName.".volt");
                    chdir($baseCwd);
               }

                // I could use :
                // $compiler->getCompiledTemplatePath()  
                // but wont work if compiler has not compiled

                include $VALUE_I_WANT_TO_KNOW;

            }catch (Exception $e){
                echo $e->getMessage();
            }

As you see in the above example, i compile only once every 1hour. But if i dont compile, i cant use $compiler->getCompiledTemplatePath() Then i use a variable $VALUE_THAT_I_WANT_TO_KNOW. In the above example, the value is not initialized for true. i could have done :

<?php
$VALUE_THAT_I_WANT_TO_KNOW = __DIR__."/views_compiled/". str_replace(array("/","\\"),"%%",realpath(__DIR__."/views/$templateName.volt") );

It would work, but it is painfull when you know it would be really more convenient, and really better for code integrity to get the compiled path from the compiler, based on the compiler option, even if we didnt compile it before.

For example :

<?php
    $compiler->getCompiledPathEvenIfIdidntCompileIt("$templateName.volt");

Is there a method for that ?



85.3k

Templates are only compiled if the compiled path modification time is greater than the original template file modification time, doing this would not add any improvement.

Of course, what you need is not supported, since the compile() method is not called, template-path is not being processed.

You can extend the compiler and add that method:

class MyCompiler extends \Phalcon\Mvc\View\Engine\Volt\Compiler
{
    public function getCompiledPathEvenIfIdidntCompileIt($templatePath)
    {
        $options = $this->_options;
        //...
    }
}

Indeed if the built-in does not offer method for that, extending is the best !

Thanks Phalcon