Menu Close
    Start a Project Request quote Reading list Switch to dark mode
    marketplace-mod

    ViewModel and SRP in Magento 2

    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”

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

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

    Now let’s create a ViewModel,

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

    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.!!!!!

    . . .

    Comment

    Add Your Comment

    Be the first to comment.

    Back to Top
    css.php
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again
    Close