Skip to content

How can I inject behavior before a phrase is rendered in Magento 2?

I’m working with Magento 2 and I need to modify a Phrase before it gets rendered.

Is there a recommended way to hook into this process or modify the behavior of the __() function before the translated string is rendered?

For example, I might want to perform some checks, modifications, or apply additional logic to the string before it gets output.

Any guidance or best practices for achieving this in Magento 2 would be greatly appreciated!

What I have tried so far

I have tried extending MagentoFrameworkPhrase

class Phrase extends MagentoFrameworkPhrase
{

    public function __construct($text, $arguments = [])
    {
        parent::__construct($text, $arguments);
    }

    public function __toString()
    {
        // Implement some custom behaviour here
        return parent::__toString();
    }
}

If im correct, this doesn´t work because Magento 2 often just creates new Phrases and doesn´t inject them, so setting my preference in the di.xml is no use.