Read More
Read More
Menu Close

    How Getter Setter Automatically Generated in Magento?

    Most of us do not create a getter or setter method for DB fields in model class but still while calling these methods why it doesn’t through any error?

    So in Magento, everything is used as an object and each model class somewhere extends \Magento\Framework\DataObject::class in the parent. In this class __call method is actually responsible for the generation of getter and setter of any field (for e.g, setName($name) or getName()).

    Let’s check its implementation.

    /**
         * Set/Get attribute wrapper
         *
         * @param   string $method
         * @param   array $args
         * @return  mixed
         * @throws \Magento\Framework\Exception\LocalizedException
         */
        public function __call($method, $args)
        {
            switch (substr($method, 0, 3)) {
                case 'get':
                    $key = $this->_underscore(substr($method, 3));
                    $index = isset($args[0]) ? $args[0] : null;
                    return $this->getData($key, $index);
                case 'set':
                    $key = $this->_underscore(substr($method, 3));
                    $value = isset($args[0]) ? $args[0] : null;
                    return $this->setData($key, $value);
                case 'uns':
                    $key = $this->_underscore(substr($method, 3));
                    return $this->unsetData($key);
                case 'has':
                    $key = $this->_underscore(substr($method, 3));
                    return isset($this->_data[$key]);
            }
            throw new \Magento\Framework\Exception\LocalizedException(
                new \Magento\Framework\Phrase('Invalid method %1::%2', [get_class($this), $method])
            );
        }

    This __call() method is a magic method in PHP that executes when a call to an undefined method is made. So whenever we call any undefined method over a model object, the __call() methods checks for the get, set, uns, has prefixes in the called method name, then check for the field name and if all goes good we haven’t face any issue and we get the desired result.

    Thanks For Reading.
    Happy Coding 🙂

    Start your headless eCommerce
    now.
    Read More
    . . .
    Discuss on Helpdesk

    Leave a Comment

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


    Be the first to comment.

    Back to Top