3

I have a question about best practices in templates.

Let's assume I am editing the product details template file. I would like to call a method in the product model which can raise an exception.

What is the best way to proceed :

  • to put the call in a verbose try / catch in the template, displaying the appropriate result in case of success/failure ;
try {
    echo $product->getSomething()->getName();
} catch (NoSuchEntityException $ex) {
    echo "No related Something";
} catch (\Exception $ex)) {
    echo "An error occured while extracting the related Something";
}
  • or creating an intermediate method (in the block ?), handling the try catch and returning and array with the result (if success) and a possible message, to make the template cleaner?
$result = $block->getSomething();
if($result['message'] === "") { // Everything went well
    echo $result['Something']->getName();
} else { // Something went wrong
    echo $result['message'];
}
6

In my opinion templates don't have to contain any logic on that point.
If we take your exemple, the best way is to make the try / catch in the block, the template is here only to display data.

Block file

<?php

class Foo extends \Magento\Framework\View\Element\Template
{
    [...]
    public function getName()
    {
        [...]
        try {
            return $product->getSomething()->getName();
        } catch (NoSuchEntityException $ex) {
            $this->logger->critical($ex);

            return false;
        } catch (\Exception $ex)) {
            $this->logger->critical($ex);

            return false;
        }
    }
}

Template file

<?php
/** @var string|false $name */
$name = $block->getName();
?>

[...]
<?php if ($name): ?>
   // logic...
<?php endif; ?>

In your case you can imagine different types of return in your block function and test them on your template to display the right information.

  • 1
    Exactly this. Templates should be as dumb as possible and only do stuff like if, else, echo and first-class $block-methods. Anything else is not the responsibility of the template and breaks the S.O.L.I.D. principle at that point. The only responsibility a template has is render data to HTML, not the logic that determines what the data is or if it should be rendered (example: <?php if ($block->hasName()) : ?><h1><?php echo $block->getName(); ?></h1><?php endif; ?>) – Giel Berkers Mar 16 '17 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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