skip to Main Content

I have below code in model of Magento2 custom module. As I know constructor can be define using __construct() but in below code they used _construct().I want to know the difference between two. Can it be a function ?

use MagentoFrameworkModelResourceModelDbAbstractDb;

class Post extends AbstractDb
{
    /**
     * Post Abstract Resource Constructor
     * @return void
     */
    protected function _construct()
    {
        $this->_init('myblog', 'post_id');
    }
}

3

Answers


  1. Chosen as BEST ANSWER

    I got answer and mentioning here if someone have any confusion for the same. In reference to Magento2 , single-underscore construct method is a legacy code from Magento 1 and it is called in real _construct method of MagentoFrameworkModelAbstractModel.


  2. _construct is not constructor its a method like other methods. Where __construct is the default constructor.

    For details (__construct and _construct)

    Login or Signup to reply.
  3. Single underscore construct (_construct) is used to avoid overriding the actual constructor with double underscore (__construct).

    Example: vendor/magento/framework/Model/ResourceModel/AbstractResource.php

        /**
         * Constructor
         */
        public function __construct()
        {
            /**
             * Please override this one instead of overriding real __construct constructor
             */
            $this->_construct();
        }
    
        /**
         * Resource initialization
         *
         * @return void
         */
        abstract protected function _construct();
    

    Related question with more answers: Why does Magento have _construct and __construct methods?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search