0

This is the code I copied from MagePlaza.

class Index extends \Magento\Framework\App\Action\Action
{
    protected $_pageFactory;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $pageFactory)
    {
        $this->_pageFactory = $pageFactory;
        return parent::__construct($context);
    }

    public function execute()
    {
        return $this->_pageFactory->create();
    }
}

How we will decide that here we need to use PageFactory and why we pass Magento\Framework\App\Action\Context in the constructor.

Can anyone help me out this please?

0

Factories are used everywhere where you need one or multiple instances of same Class.

If you use class itself to load your specific object instead, it will act like Singleton, so it will be same instance on every occurrences of that class object not constructed with Factory.

The Context is used to tell Magento in which context you are in. For example if you want to get some request data or use registry to load or save some data, you will need to take Context in mind, because data could be different in different places.

4
  • Thank you @dudzio for your response. I understood the concept of Factory and Context . But still I have one confusion regarding the Factory. Sometimes I see people use $_typeFactory and sometimes use $_objectFactory. How we decide this which type of factory we need to use? – ajaysingh Jun 17 at 5:41
  • Factories are autogenerated most of time, every generated factory is stored inside generated, there is no difference in those generated classes. Could you point me to the class containing both factories you are talking about? $_typeFactory have that name because of Class name. For example\Magento\Eav\Model\Entity\TypeFactory which is Factory for \Magento\Eav\Model\Entity\Type, but there is nothing more special in it. – dudzio Jun 17 at 7:40
  • Thank you @dudzio for detailed explanation. – ajaysingh Jun 18 at 22:24
  • You're welcome. Please accept the answer if it meet your expectations :) – dudzio Jun 20 at 6:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.