Very often it is needed to add some custom logic to templates. For example it can be checking if customer is logged or some information about product - if it's already bought by current customer or if it's already in cart. The thing is how to do it in best way. There are many many ways to do it. Of course I am not wondering if it should be done in custom module or in theme, because it depends if it's more universal issue or just something needed only in theme.
First of all you can do it just writing some php code in your templates, but of course it not elegant and makes a real mess in your code.
Second way is to make
preference on block, which is connected with templates we want to 'extend', but here comes drawbacks of overriding core files and in case that our functionality is needed in many places it's not efficient to override multiple blocks. Can't be used just for one theme, so it can break another ones if made in module for only one theme needs.
Third possible manner is to make a plugin on desired method and it works fine as long as it is not completely custom logic that needs some separate classes. So it can be achieved like this in many cases. Can't be used just for one theme, so it can break another ones if made in module for only one theme needs.
Fourth idea is to create new block, not necessarily with custom template. It can be just container for bunch of php methods. It can be easily added in any template using layout xmls and
getChildBlock() method inside phtml. Although I am not sure if it is efficient to do it like this.
Last way I have figured out is to create custom helper classes, which can be easily called in any template just by using
$this->helper('path\to\class') It is more portable way to add some logic, although helper needs to extend from it's abstract parent, so I am not sure here if it efficient. Also helper classes are discouraged from using, as not suiting anythin well, so code seems to be not well planned.
Has anyone well-checked way to achieve that? I would be extremely useful to hear points for any of these way, as well as discovering new ways to achieve that.