Best Way To Create A Functions File

Hi what is the best way to create a custom functions file in Yii2 ?

I want to create a custom functions file and add them to twig so I want to create a file called function.php and twig_helpers.php in config folder …

config folder is the right place to do this or am I have to create a folder called functions but where ??

If I do composer update, which folders or files would not be deleted ???

Thanx …

Just create it and include in your index.php just before ->run() call. This way you’ll have configured app accessible in these functions.

Composer deals with vendors dir only.

Thank you very much : )

so where can I add this to include a twig function ?

In index.php I can include the functions file. But I need to include this twig_helpers.php after twig has loaded and I have to get twig object so I can add function to it. But it define in viewrenderer.php and use config. How can I reach it and add my custom function with a file.

So in index.php before ->run twig has loaded or not ? Because in my twig_helpers.php there is a lot of functions like this .

How can I define or get twig object so I can add functions to twig on yii2.

//How can I get twig or how can I add functions to twig in yii2 ??

$function = new Twig_SimpleFunction('some_function', 'some_function');


twig is a separate thing. Check extension docs, there’s config for custom functions.

Hi I want to call all of my functions from one file. I do not know how to do this and the extension document is very poor I don’t understand how to use my functions and where to call them …

Use extension to combine functions into file like I did recently:

Thank you a lot I think I understand what to do …

I am gonna create a class which extends \Twig_Extension like you did … Is it true ??

Because I do not want to add a code in your file with a composer update it will be gone away.

Just one question, I have created a class which extends \Twig_Extension and save it file to anywhere in my project. Than how can I load it or call it or where ?? I am gonna search the proper way for it, I do not want to choose a way on my own …

Sorry I am really a newbie for yii, I have never used it before so I am trying to understand…

I have created a file called TwigHelpers.php and save it in components folder

namespace yii\twig;

class TwigHelpers extends \Twig_Extension




    public function getFunctions()


       $options = [

            'is_safe' => ['html'],


        $functions = [

            new \Twig_SimpleFunction('test', [$this, 'testprice'], $options),




		return $functions;


    public function testprice($var)


        return $var;


    public function getName()


        return 'yii2-twig';




But when I call from twig file {{test(1)}} I get this error

The function "test" does not exist…

So where do I wrong ??

You haven’t configure twig to use extension.