We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How to call a method of class in Volt

Hi all

I have a question, I suppose a libray is VoltFunctions

<?php

namespace Zphalcon\Tools;

/**
 * PHP Functions in Volt
 */
class VoltFunctions
{

    /**
     * Compile any function call in a template
     *
     * @param string $name function name
     * @param mixed $arguments function args
     *
     * @return string compiled function
     */
    public function compileFunction($name, $arguments)
    {
        if (function_exists($name)) {
            return $name . '(' . $arguments . ')';
        }

        if ($name == 'dump') {
            return '\Phalcon\Debug\Dump::all(' . $arguments . ')';
        }
    }

    /**
     * Compile some filters
     *
     * @package     las
     * @version     1.0
     *
     * @param string $name filter name
     * @param mixed $arguments filter args
     *
     * @return string compiled filter
     */
    public function compileFilter($name, $arguments)
    {
        if ($name == 'isset') {
            return '(isset(' . $arguments . ') ? ' . $arguments . ' : null)';
        }
        if ($name == 'long2ip') {
            return 'long2ip(' . $arguments . ')';
        }
    }

    /**
     * Get either a Gravatar URL or complete image tag for a specified email address.
     *
     * @param string $email The email address
     * @param string $s Size in pixels, defaults to 80px [ 1 - 2048 ]
     * @param string $d Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
     * @param string $r Maximum rating (inclusive) [ g | pg | r | x ]
     * @param boole $img True to return a complete IMG tag False for just the URL
     * @param array $atts Optional, additional key/value attributes to include in the IMG tag
     * @return String containing either just a URL or a complete image tag
     */
    public  function getAvatar($email ,$s = 80, $d = 'mm', $r = 'g', $img = false, $atts = array())
    {
        /*$path = '/images/u/' . $this->getId() . '-thumb.jpg';
        if (file_exists(PUBLIC_DIR.$path)) {
            return $path;
        }*/
        $url = 'http://www.gravatar.com/avatar/';
        $url .= md5( strtolower( trim( $email ) ) );
        $url .= "?s=$s&d=$d&r=$r";
        if ( $img ) {
            $url = '<img src="' . $url . '"';
            foreach ( $atts as $key => $val )
                $url .= ' ' . $key . '="' . $val . '"';
            $url .= ' />';
        }
        return $url;
    }

}

And in file service I have defined it below:

 //  Setting up the view component
        $di->set(
            'view',
            function () use ($config) {
                $view = new View();
                $view->setViewsDir($config->application->view->viewsDir);
                $view->disableLevel([View::LEVEL_MAIN_LAYOUT => true, View::LEVEL_LAYOUT => true]);
                //@TODO: move to an extensions/filters/functions file.
                $view->registerEngines(
                    [
                        '.volt' => function () use ($view, $config) {
                                $volt = new Volt($view);
                                $volt->setOptions(
                                    [
                                        'compiledPath'      => $config->application->view->compiledPath,
                                        'compiledSeparator' => $config->application->view->compiledSeparator,
                                        'compiledExtension' => $config->application->view->compiledExtension,
                                        'compileAlways'     => $config->application->debug,
                                    ]
                                );
                                $compiler = $volt->getCompiler();
                                $compiler->addExtension(new Zphalcon\Tools\VoltFunctions());
                                $compiler->addFunction(
                                    't',
                                    function ($string) {
                                        return t($string);
                                    }
                                );
                                $compiler->addFunction('array_key_exists', 'array_key_exists');
                                $compiler->addFilter(
                                    'truncate',
                                    function ($str, $maxLen = 35, $suffix = '...') {
                                        return 'Zphalcon\Models\Tools::truncate(' . $str . ')';
                                    }
                                );
                                $compiler->addFunction(
                                    'urls',
                                    function ($email) {
                                        return 'Zphalcon\Tools\VoltFunctions::abc(' .$email. ')';
                                    }
                                );
                                return $volt;
                        }
                    ]
                );
                return $view;
            }
        );

As you see document here http://docs.phalcon.io/en/latest/reference/volt.html#extensions

How to call method getAvatar of class VoltFunction in volt ?



33.7k

Unless you use an instance for invoking the method, you'll have to do the same as me (and you): creating a Volt function per class method.

That's the only thing worked for me time ago.

// What I don't remember is that maybe you've to declare it static...
// '$resolvedArgs' is a string that contains all the params used calling the function in a Volt template.

$compiler->addFunction('getAvatar', function ($resolvedArgs) {
    return ('Zphalcon\Tools\VoltFunctions::getAvatar(' . $resolvedArgs . ')');
});


58.2k

Yes, I know add a function this is working, but some time we have many function , I don't add in file service.php, I mean move to an extensions/filters/functions a file VoltFunction.php, Then in service call it



58.2k
Accepted
answer

Ok,

I have just solve it, just create Class, then in method compileFunction add it, for example

public function compileFunction($name, $arguments)
    {

        if (function_exists($name)) {
            return $name . '(' . $arguments . ')';
        }

        if ($name == 'dump') {
            return '\Phalcon\Debug\Dump::all(' . $arguments . ')';
        }

        if ($name == 'getAvatar') {
            //return $arguments;
            $a = self::getAvatar($arguments);
           return '\Zphalcon\Tools\ZFunction::getAvatar('. $arguments .')';
        }
        //echo "<pre>";
        //var_dump(__FUNCTION__);
        //var_dump($name, $arguments);
    }

Here we have defined a class ZFunction with method static is getAvatar