Reading list Switch to dark mode

    ViewModel and SRP in Magento 2

    Updated 5 January 2023

    Before studying ViewModel feature of magento, let’s understand first SRP.
    SRP stands for Single Responsibility Principle : Every class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class.
    In simple words : Each class should ideally have only one purpose to change.
    Basically this is a part of SOLID Principle of Software Development.

    VIEW MODEL :
    View model is class that we inject to phtml, so that require and related data could be access from it.
    View Model helps us to avoid unnecessary overriding of the block class Magento\Framework\View\Element\Template ‘s constructor .

    View Model Implementation :
    To implement the view model, we need to add the argument in block arguments with xsi type object as xsi:type=”object”

    <block name="custom.block" template="Vendor_Module::custom.phtml">
        <arguments>
            <argument name="view_model" xsi:type="object"><Vendor>\<Module>\ViewModel\Custom</argument>
        </arguments>
    </block>

    To create the view model we need to implement the Argument Interface.

    \Magento\Framework\View\Element\Block\ArgumentInterface;

    Now let’s create a ViewModel,

    <?php
    /**
     * Webkul Software.
     *
     * PHP version 7.0+
     *
     * @category  Webkul
     * @package   Webkul_Test
     * @author    Webkul <[email protected]>
     * @copyright Webkul Software Private Limited (https://webkul.com)
     * @license   https://store.webkul.com/license.html ASL Licence
     * @link      https://store.webkul.com/license.html
     */
    namespace <Vendor>\<Module>\ViewModel;
    
    use Magento\Framework\View\Element\Block\ArgumentInterface;
    
    class Custom implements ArgumentInterface
    {
    // Do some stuff here.
    }

    To get the View model in phtml file, we just need to call the name of the argument via block reference as follows

    Start your headless eCommerce
    now.
    Find out More
    /** @var \Magento\Framework\View\Element\Template $block*/
    $block->getData("view_model");
    //OR
    $block->getViewModel();

    Conclusion :
    With the help of viewModel , it benefits us that we don’t need to create the block class and inject the unnecessary Injection of the Dependencies and call parent.
    Most importantly it help us to implement SOLID Property SRP.

    That all for now, Happy coding.!!!!!

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home