Magento 2 – Best Place to Put Custom Function

classmagento2methodstemplate

I've created a little function for one of my template (.phtml) files which I'd like to re-use in a few other template files. All the function does is concatenate a couple of strings together and trim them – its use / function is not relevant. I'm guessing you could call it a utility function.

As it'd like to re-use the function in a few template files, where would the best place for me to place the function so it's available to all templates? I would like to define the function in one place, so I can update / amend / expand upon it in the future – wihtout having to go into every file it's being used in… (DRY!)

I'm guessing it should be placed in a Class and turned into a method? If so, which Class and why?

Best Answer

You could put it in a helper class. Here's an example

{module_directory}/Helper/StringHelper.php :

<?php

namespace Your\Module\Helper;


use Magento\Framework\App\Helper\AbstractHelper;

class StringHelper extends AbstractHelper
{

    function stringFunc($string)
    {
        return $string . ' helped';
    }

}

In your template file :

<?php echo $this->helper('Your\Module\Helper\StringHelper')->stringFunc('test') ?>
Related Topic