Reading list Switch to dark mode

    How to use a strategy design pattern in Magento2?

    Updated 1 April 2023

    What is a strategy design pattern?

    Strategy pattern is known as Policy Pattern also.

    The Strategy design pattern allows you to take a class that does something specific in a lot of different ways and extracts all of these algorithms into separate classes called strategies.

    Use a strategy design pattern to avoid writing multiple if else statements or switch cases to perform some event.

    Example:- If you want to trigger a custom notification after placing an order according to order status so to perform this event you have to use multiple if else statements or switch cases and you have to write extra lines of code to do your task to call the method for each state. use the strategy design pattern to perform this task by writing a few lines of code in place of multiple if-else statements or switch cases.

    Searching for an experienced
    Magento 2 Company ?
    Find out More

    How to use the strategy pattern

    1) Create file etc/frontend/di.xml in your module to define the order status and methods. Those you want to call according to order status.

    <?xml version="1.0"?>
    
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
        <type name="Webkul\Custom\Helper\Data">
            <arguments>
                <argument name="orderStatus" xsi:type="array">
                    <item name="order_status" xsi:type="array">
                        <item name="new" xsi:type="string">newState</item>
                        <item name="processing" xsi:type="string">processingState</item>
                        <item name="holded" xsi:type="string">holdedState</item>
                        <item name="canceled" xsi:type="string">canceledState</item>
                        <item name="complete" xsi:type="string">completeState</item>
                    </item>
                </argument>
            </arguments>
        </type>
    </config>
    
    Use the type declaration to add the arguments in your class constructor parameters.

    2) Create \Helper\Data.php in your module as we have defined the type “Webkul\Custom\Helper\Data” in di.xml. We are using the helper to load the arguments. So we can use it all over the class as per requirements.

    <?php
    
    namespace Webkul\Custom\Helper;
    
    /**
     * MpNotifications data helper
     */
    class Data extends \Magento\Framework\App\Helper\AbstractHelper
    {
    
        /**
         * Construct
         *
         * @param \Magento\Framework\App\Helper\Context $context
         * @param array $orderStatus
         */
        public function __construct(
            \Magento\Framework\App\Helper\Context $context,
            $orderStatus = []
        ) {
            parent::__construct($context);
            $this->orderStatus = $orderStatus;
        }
    
    
        /**
         * Return method array
         *
         * @param string $type
         * @return array
         */
        public function getMethodArray($type)
        {
            return $this->orderStatus[$type];
        }
    
    }
    

    3) Create file Webkul\Custom\Observer\SalesOrderChangeStateAfterObserver.php for the event sales_order_save_after

    <?php
    
    namespace Webkul\Custom\Observer;
    
    use Magento\Framework\Event\ObserverInterface;
    
    class SalesOrderChangeStateAfterObserver implements ObserverInterface
    {
        public const ORDER_STATUS = 'order_status';
    
        /**
         * @var $_ordersFactory
         */
        protected $_ordersFactory;
    
        /**
         * Constructor
         *
         * @param \Magento\Sales\Model\OrdersFactory $ordersFactory
         * @param \Webkul\Custom\Helper\Data $dataHelper
         */
        public function __construct(               \Magento\Sales\Model\OrdersFactory $ordersFactory,
            \Webkul\Custom\Helper\Data $dataHelper
        ) {
            $this->_ordersFactory = $ordersFactory;
            $this->_dataHelper = $dataHelper;
        }
    
        /**
         * Sales Order Change State After
         *
         * @param \Magento\Framework\Event\Observer $observer
         */
        public function execute(\Magento\Framework\Event\Observer $observer)
        {        
              try {
                            $order = $observer->getEvent()->getOrder();
                        
                            $orderId = $order->getId();
                            $orderFactory = $this->_ordersFactory->create();
                            $methodArray = $this->_dataHelper->getMethodArray(self::ORDER_STATUS);
                            if (!empty($order->getState())) {
                                $method = $methodArray[$order->getState()];
                                $this->$method($orderId, $order, $orderFactory);
                            }
                }
        }
    
        /**
         * New state
         *
         * @param int $orderId
         * @param object $order
         * @param object $orderFactory
         */
        private function newState($orderId, $order, $orderFactory)
        {
          // Wrrite your code here
        }
    
    }
    
    How to use a strategy design pattern

    . . .

    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