2

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?

1 Answer 1

6

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.