1

I need to show a list of latest reviews on magento 2 homepage. I did it this way

<?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$reviewCollection = $objectManager->create('Magento\Review\Model\ResourceModel\Review\CollectionFactory');
$collection = $reviewCollection->create()->load();

foreach ($collection as $review){
 echo $review->getTitle().'<br>';
}  ?>

But I feel like its a bad practice, is there a better solution?

1 Answer 1

0

There are always better solutions.

In order to make these kind of things more reusable, one better way would be to make your reviews into a widget. Create etc/widget.xml in your module and point it to a Block class that you create.

In that Block class you can set a mytemplate.phtml template. Now you have separated the code from the layout, which is a better way. Also widgets can have configuration parameters, for example you could make the number configurable after which you stop displaying reviews (imagine there are thousands of reviews in your system, you probably don't want to load them all).

Furthermore, the ObjectManager should never be used directly. Instead, your CollectionFactory should be instantiated through Dependency Injection in the constructor. Alan Storm has written a very good tutorial about that.

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.