Defining view helper

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



83.5k

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); ?>


12.6k

Thanks, But I want access to the functions directly.

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



83.5k

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";