Lets start by a practical example to better understand what is dependency injection in Magento 2.

    Lets say we need to get product collection on a page.A simple module will do this job for us. Although there are methods as well to achieve this.

    /** @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory */
    protected $collectionFactory;
    public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory
    ) {
        $this->collectionFactory = $collectionFactory;
    public function yourMethod()
        // Use factory to create a new product collection
        $productCollection = $this->collectionFactory->create();
        /** Apply filters here */
        // Don't have to do this
        // $productCollection->load();
        foreach ($productCollection as $product){
             echo 'Name  =  '.$product->getName().'<br>';

    About Author

    You may also like

    No Comment

    You can post first response comment.

    Leave A Comment

    Please enter your name. Please enter an valid email address. Please enter a message.