We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Defining view helper

I use PHP as my templating language. How can I define some helper function ?



98.9k

You can create a helper class:

<?php

class Helpers 
{

    public function sum($argument1, $argument2)
    {
        return $argument1 + $argument2;
    }

}

Then register the class in the di:

$di->set('helpers', function(){
    return new Helpers();
});

Then in the views:

<?php echo $this->helpers->sum(1, 2); ?>


22.1k

Thanks, But I want access to the functions directly.

\\in text.phtml
<?=sum(1, 2); ?>


98.9k

Functions don't support autoloaders, assuming you have a file with helpers:

<?php
// app/helpers/view.php

function sum($argument1, $argument2)
{
    return $argument1 + $argument2;
}

You can make a global require to make those functions available for the views, for example in (public/index.php):

require "../app/helpers/view.php";