View models magento

Use ViewModels anytime you need to inject functionality into template files. This is a clean approach to distribute logic from block classes into separate classes that are easier to maintain, understand, test, and reuse.

Step 1: Define view mode in layout.xml file (last_order is the name used in this configuration, you are free to use any name)

<block name="module.customer.lastorder"
        <argument name="last_order" xsi:type="object">Module\Customer\ViewModel\LastOrder

Step 2: Access your view model in your template, remember last_order you defined in step 1

/** @var \Module\Customer\ViewModel\LastOrder $lastOrder */
$lastOrder = $block->getData('last_order');
$lastOrder->getLastOrder(100); // just any number

Step 3: Your ViewModel class

namespace Module\Customer\ViewModel;

use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\View\Element\Block\ArgumentInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\OrderRepository;

class LastOrder implements ArgumentInterface
    /** @var OrderRepository  */
    private $orderRepository;

     * LastOrder constructor.
     * @param OrderRepository $orderRepository
    public function __construct(OrderRepository $orderRepository)
        $this->orderRepository = $orderRepository;

     * @param int $orderId
     * @return Order
     * @throws InputException
     * @throws NoSuchEntityException
    public function getLastOrder(int $orderId): Order
        return $this->orderRepository->get($orderId);

what clients say about us

Client testimonials

Our sites look great and run smoothly. Thanks for all your hard work and patience in getting us to where we are today.

contact us

Contact Us

If you have questions or want us to send you a quote for project please email us.

latest news


PHPUnit mock magic functions
Learn more about PHPUnit Partial Mock.