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 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">
            <argument name="view_model" xsi:type="object"><Vendor>\<Module>\ViewModel\Custom</argument>

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


    Now let’s create a ViewModel,

     * Webkul Software.
     * PHP version 7.0+
     * @category  Webkul
     * @package   Webkul_Test
     * @author    Webkul <[email protected]>
     * @copyright Webkul Software Private Limited (
     * @license ASL Licence
     * @link
    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
    Find out More
    /** @var \Magento\Framework\View\Element\Template $block*/

    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