Module 1: Magento 2 Fundamentals

What is Magento 2?

Magento 2 is a powerful open-source eCommerce platform used to build scalable and customizable online stores. It is widely used by businesses for its flexibility, performance, and rich feature set.

Magento follows a modular architecture and supports customization at every level including frontend, backend, and APIs.

Key Features:

  • Open-source and highly customizable
  • Supports large product catalogs
  • Multi-store and multi-language support
  • SEO-friendly architecture
  • Advanced user roles and permissions

Editions: Open Source vs Adobe Commerce

Feature Magento Open Source Adobe Commerce
Cost Free Paid
Cloud Hosting No Yes
B2B Features No Yes
Support Community Official Adobe Support

Exam Tip: Adobe Commerce includes additional enterprise features like B2B modules, staging, and advanced security.

Magento 2 Architecture Overview

Magento 2 follows the MVC (Model-View-Controller) architecture and a modular system.

MVC Breakdown:

  • Model: Handles data and business logic
  • View: UI (PHTML, XML, UI Components)
  • Controller: Handles requests and responses

Modular System:

Magento is divided into independent modules. Each module handles specific functionality and can be enabled/disabled independently.

Exam Tip: Magento is NOT a pure MVC system — it uses service contracts and dependency injection.

Magento 2 File Structure


app/
 ├── code/
 ├── design/
 ├── etc/

vendor/
pub/
var/
generated/

Important Directories:

  • app/code: Custom modules
  • vendor: Composer packages
  • pub: Public accessible files
  • var: Cache, logs

Exam Tip: Never modify code inside vendor folder.

Deployment Modes

Mode Description
Developer Used during development, shows errors
Production Optimized for performance, hides errors
Default Hybrid mode (not recommended)

Command:


php bin/magento deploy:mode:set developer
php bin/magento deploy:mode:set production

Exam Tip: Production mode disables error display and enables static content deployment.

Practice MCQs

  1. What is Magento 2?

    A) CMS
    B) eCommerce Platform ✅
    C) Programming Language
    D) Database
  2. Which architecture does Magento follow?

    A) MVC ✅
    B) MVVM
    C) Monolithic
    D) None
  3. Where should custom modules be placed?

    A) vendor/
    B) pub/
    C) app/code/ ✅
    D) var/
  4. Which mode is best for development?

    A) Production
    B) Default
    C) Developer ✅
    D) Safe Mode
  5. Can we modify vendor code directly?

    A) Yes
    B) No ✅

Scenario-Based Questions

Q1: You need to debug errors in Magento. Which mode should you use?

Answer: Developer Mode

Q2: Your site is live and performance is slow. What should you enable?

Answer: Production Mode + Caching

Q3: You want to customize core functionality. Should you edit vendor files?

Answer: No, create a custom module.

Module 2: Magento 2 Module Development (Core)

Subtitle: Learn how to create, structure, and control Magento 2 modules

Module Structure

A module in Magento 2 is a self-contained unit that contains business logic. Each feature in Magento is built using modules.


app/code/Vendor/Module/
├── registration.php
├── etc/
│   └── module.xml
├── Controller/
├── Model/
├── view/

Exam Tip: Every module must have registration.php and module.xml.

registration.php

This file registers your module with Magento.


use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(
    ComponentRegistrar::MODULE,
    'Vendor_Module',
    __DIR__
);

Exam Tip: Module name must follow Vendor_Module format.

module.xml

Defines module name and version.


<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">

    <module name="Vendor_Module" setup_version="1.0.0"/>

</config>

Exam Tip: Used for module declaration and dependency.

Routes (frontend & adminhtml)

Routes define how URLs map to controllers.

Frontend Route:


app/code/Vendor/Module/etc/frontend/routes.xml

<router id="standard">
    <route id="custom" frontName="custom">
        <module name="Vendor_Module"/>
    </route>
</router>

URL: yourdomain.com/custom/index/index

Exam Tip: frontName defines URL path.

Controllers

Controllers handle HTTP requests and return responses.


namespace Vendor\Module\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;

class Index extends Action
{
    public function __construct(Context $context)
    {
        parent::__construct($context);
    }

    public function execute()
    {
        echo "Hello Magento 2";
    }
}

Exam Tip: execute() method is mandatory.

Dependency Injection (di.xml)

Magento uses Dependency Injection to manage class dependencies.


<type name="Vendor\Module\Model\Example">
    <arguments>
        <argument name="param" xsi:type="string">value</argument>
    </arguments>
</type>

Exam Tip: Object Manager should not be used directly.

Preferences vs Plugins vs Observers

Method Usage
Preference Override entire class
Plugin Modify specific methods
Observer Listen to events

Exam Tip: Plugins are preferred over preferences.

Practice MCQs

  1. Which file is required to register a module?

    A) module.xml
    B) registration.php ✅
    C) routes.xml
    D) di.xml
  2. What is correct module naming convention?

    A) module_vendor
    B) Vendor_Module ✅
    C) vendor-module
    D) ModuleVendor
  3. Which file defines routes?

    A) di.xml
    B) routes.xml ✅
    C) module.xml
    D) config.xml
  4. Which method is mandatory in controller?

    A) init()
    B) run()
    C) execute() ✅
    D) start()
  5. Best way to modify existing method behavior?

    A) Preference
    B) Plugin ✅
    C) Observer
    D) Override core

Scenario-Based Questions

Q1: You want to change only one method in a core class. What will you use?

Answer: Plugin

Q2: You want to completely replace a class. What will you use?

Answer: Preference

Q3: You want to trigger code when order is placed. What will you use?

Answer: Observer (event-based)

Q4: Your custom module is not working. What two files must exist?

Answer: registration.php and module.xml

Module 3: Database & Models in Magento 2

Subtitle: Learn Models, Resource Models, Collections, and Database Schema

Models, Resource Models & Collections

Magento follows a layered architecture for database interaction:

  • Model: Business logic
  • Resource Model: Database operations (CRUD)
  • Collection: Fetch multiple records

Flow:

Model → Resource Model → Database

Exam Tip: Models do NOT directly interact with database.

Model Example


namespace Vendor\Module\Model;

use Magento\Framework\Model\AbstractModel;

class Post extends AbstractModel
{
    protected function _construct()
    {
        $this->_init(\Vendor\Module\Model\ResourceModel\Post::class);
    }
}

Exam Tip: _init() links model with resource model.

Resource Model

Resource Model handles database operations like insert, update, delete.


namespace Vendor\Module\Model\ResourceModel;

use Magento\Framework\Model\ResourceModel\Db\AbstractDb;

class Post extends AbstractDb
{
    protected function _construct()
    {
        $this->_init('vendor_post', 'id');
    }
}
  • vendor_post → table name
  • id → primary key

Collection

Collections are used to retrieve multiple records.


namespace Vendor\Module\Model\ResourceModel\Post;

use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;

class Collection extends AbstractCollection
{
    protected function _construct()
    {
        $this->_init(
            \Vendor\Module\Model\Post::class,
            \Vendor\Module\Model\ResourceModel\Post::class
        );
    }
}

Exam Tip: Collections always extend AbstractCollection.

CRUD Operations

Create / Update


$model->setData('title', 'Test');
$model->save();

Read


$model->load($id);

Delete


$model->delete();

Exam Tip: save(), load(), delete() come from AbstractModel.

Declarative Schema (db_schema.xml)

Magento 2 uses Declarative Schema instead of install/upgrade scripts.


<table name="vendor_post" resource="default" engine="innodb">
    <column name="id" xsi:type="int" nullable="false" identity="true"/>
    <column name="title" xsi:type="text" nullable="false"/>
    <constraint xsi:type="primary">
        <column name="id"/>
    </constraint>
</table>

Exam Tip: db_schema.xml is preferred over InstallSchema.php.

Data Patch & Schema Patch

Patches are used for database changes and data insertion.

Types:

  • Schema Patch: Modify structure
  • Data Patch: Insert/update data

Example (Data Patch)


class AddSampleData implements \Magento\Framework\Setup\Patch\DataPatchInterface
{
    public function apply()
    {
        // insert data
    }
}

Exam Tip: Patches are version-independent.

Important Concepts

  • ResourceModel directly interacts with DB
  • Collection loads multiple records
  • Model contains business logic
  • db_schema.xml replaces old setup scripts

Practice MCQs

  1. Which layer interacts with database?

    A) Model
    B) Resource Model ✅
    C) Controller
    D) View
  2. Which method links model to resource model?

    A) setModel()
    B) init()
    C) _init() ✅
    D) connect()
  3. Which class is used for collections?

    A) AbstractModel
    B) AbstractDb
    C) AbstractCollection ✅
    D) CollectionFactory
  4. Which file defines database structure?

    A) di.xml
    B) module.xml
    C) db_schema.xml ✅
    D) routes.xml
  5. Which method is used to delete record?

    A) remove()
    B) delete() ✅
    C) destroy()
    D) clear()

Scenario-Based Questions

Q1: You need to fetch multiple records. What will you use?

Answer: Collection

Q2: You want to insert a new column in table. What will you use?

Answer: db_schema.xml or Schema Patch

Q3: Your model is not saving data. What could be missing?

Answer: Resource Model linkage (_init)

Q4: You need to insert default data after module install. What will you use?

Answer: Data Patch

Module 4: EAV (Entity-Attribute-Value) in Magento 2

Subtitle: Understand how Magento stores flexible product data using EAV model

What is EAV?

EAV stands for Entity-Attribute-Value. It is a database model used to store dynamic and flexible data.

Instead of storing all data in one table, Magento splits data into multiple tables based on attribute types.

Example:

  • Entity: Product
  • Attribute: Color
  • Value: Red

Exam Tip: EAV is used for products, categories, and customers.

Why Magento Uses EAV?

  • Supports unlimited attributes
  • Flexible structure (no need to alter table)
  • Efficient for large catalogs

Drawback: Complex queries and joins

EAV Table Structure

Magento stores attributes in different tables based on data type:

  • catalog_product_entity
  • catalog_product_entity_varchar
  • catalog_product_entity_int
  • catalog_product_entity_decimal
  • catalog_product_entity_text

Example: Product name → varchar table, price → decimal table

Exam Tip: Attribute backend_type decides table.

Product Attributes

Attributes define properties of products like name, price, color, size.

Types of Attributes:

  • System Attributes (predefined)
  • Custom Attributes

Important Fields:

  • attribute_code
  • backend_type
  • frontend_input
  • source_model

Attribute Sets

Attribute sets are groups of attributes assigned to products.

Example:

  • Default Attribute Set
  • Clothing Attribute Set (size, fabric)

Exam Tip: Every product must belong to one attribute set.

Create Custom Attribute (Programmatically)


$eavSetup->addAttribute(
    \Magento\Catalog\Model\Product::ENTITY,
    'custom_color',
    [
        'type' => 'varchar',
        'label' => 'Custom Color',
        'input' => 'text',
        'required' => false,
        'visible' => true,
    ]
);

Exam Tip: Use Data Patch for attribute creation.

Important Concepts

  • EAV allows dynamic attributes
  • Each attribute stored in separate table
  • backend_type determines storage table
  • Attribute sets group attributes

Practice MCQs

  1. What does EAV stand for?

    A) Entity Attribute Value ✅
    B) Event Action Value
    C) Entity Access View
    D) None
  2. Which entity uses EAV?

    A) Orders
    B) Products ✅
    C) Logs
    D) Cache
  3. Where is product price stored?

    A) varchar table
    B) decimal table ✅
    C) text table
    D) static table
  4. What decides attribute storage table?

    A) frontend_input
    B) backend_type ✅
    C) label
    D) attribute_code
  5. Can a product exist without attribute set?

    A) Yes
    B) No ✅

Scenario-Based Questions

Q1: You want to add a new product field without altering database table. What will you use?

Answer: EAV Attribute

Q2: You need to store price value. Which table will be used?

Answer: catalog_product_entity_decimal

Q3: Product attribute is not saving. What could be wrong?

Answer: Incorrect backend_type or attribute setup

Q4: You want to group attributes for clothing products. What will you use?

Answer: Attribute Set

Module 5: Layout, Blocks & Templates in Magento 2

Subtitle: Control frontend rendering using XML, PHP Blocks, and PHTML templates

Magento Frontend Architecture

Magento frontend is based on three main components:

  • Layout (XML): Structure of the page
  • Block (PHP): Business logic
  • Template (PHTML): HTML rendering

Flow: Layout → Block → Template

Exam Tip: Layout controls WHAT appears, Block controls DATA, Template controls VIEW.

Layout XML

Layout XML defines page structure and blocks.

Example:


<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <body>
        <referenceContainer name="content">
            <block class="Vendor\Module\Block\Test" 
                   name="custom.block" 
                   template="Vendor_Module::test.phtml" />
        </referenceContainer>
    </body>
</page>
  • referenceContainer: Where block will be placed
  • block: Defines PHP block + template

Block (PHP Class)

Block is responsible for passing data to template.


namespace Vendor\Module\Block;

use Magento\Framework\View\Element\Template;

class Test extends Template
{
    public function getMessage()
    {
        return "Hello Magento";
    }
}

Exam Tip: Business logic should be in Block, not in PHTML.

Template (PHTML)

Template is used to render HTML output.


<h2><?= $block->getMessage(); ?></h2>

Important: Always use $block to call methods.

Layout File Types

  • default.xml → applied globally
  • catalog_product_view.xml → product page
  • cms_index_index.xml → homepage

Exam Tip: Layout file naming = route_controller_action.xml

Containers vs Blocks

  • Container: Structure (no PHP logic)
  • Block: Contains logic + template

Example Containers: header, footer, content

Important Layout Instructions

Add Block

<block ... />

Remove Block

<referenceBlock name="block.name" remove="true"/>

Move Block


<move element="block.name" destination="header"/>

Best Practices

  • Keep logic in Block, not in template
  • Use ViewModels instead of heavy Blocks (advanced)
  • Do not write direct SQL in PHTML
  • Follow naming conventions

Practice MCQs

  1. What controls page structure?

    A) Template
    B) Block
    C) Layout XML ✅
    D) Controller
  2. Where should business logic be written?

    A) Template
    B) Block ✅
    C) XML
    D) CSS
  3. Which file is used for homepage layout?

    A) default.xml
    B) cms_index_index.xml ✅
    C) home.xml
    D) index.xml
  4. Which tag removes block?

    A) <remove>
    B) <delete>
    C) <referenceBlock remove="true"/> ✅
    D) <unset>
  5. How to call block method in template?

    A) $this->method()
    B) $block->method() ✅
    C) call()
    D) getBlock()

Scenario-Based Questions

Q1: You want to add custom block on product page. What will you use?

Answer: catalog_product_view.xml

Q2: Your data is not visible in template. What could be wrong?

Answer: Block method not defined or not called correctly

Q3: You need to remove a block from header. What will you use?

Answer: referenceBlock remove="true"

Q4: You want to shift block from footer to header. What will you use?

Answer: move instruction

Practical Assignment 🔥

Create a custom module and display message on homepage:

  1. Create module Vendor_Module
  2. Create Block class
  3. Create template file
  4. Add layout file cms_index_index.xml
  5. Display "Hello from Magento"

Bonus: Add dynamic product count

Module 6: Dependency Injection (DI) in Magento 2

Subtitle: Learn how Magento manages class dependencies using DI.xml

What is Dependency Injection?

Dependency Injection (DI) is a design pattern where objects receive their dependencies from outside instead of creating them internally.

Without DI (Wrong Way)


$object = new Product();

With DI (Correct Way)


public function __construct(
    \Magento\Catalog\Model\Product $product
) {
    $this->product = $product;
}

Exam Tip: Avoid using ObjectManager directly.

Object Manager

Object Manager is responsible for creating objects and injecting dependencies.

  • Handles class instantiation
  • Manages dependencies
  • Reads di.xml configuration

Important: Do NOT use ObjectManager directly in code.

di.xml File

di.xml is used to configure dependency injection.

Location:


app/code/Vendor/Module/etc/di.xml

Example:


<type name="Vendor\Module\Model\Test">
    <arguments>
        <argument name="message" xsi:type="string">Hello DI</argument>
    </arguments>
</type>

Constructor Injection

Magento uses constructor injection to pass dependencies.


public function __construct(
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
) {
    $this->scopeConfig = $scopeConfig;
}

Exam Tip: Dependencies are injected via constructor automatically.

Types of DI Configuration

  • Type: Configure specific class
  • Preference: Override class
  • Virtual Type: Create modified instance

Preference (Class Override)

Preference is used to override a class globally.


<preference for="Magento\Catalog\Model\Product"
            type="Vendor\Module\Model\CustomProduct"/>

Warning: Use preference carefully (can break core behavior).

Virtual Types

Virtual types allow modifying class behavior without overriding it.


<virtualType name="CustomLogger"
             type="Magento\Framework\Logger\Monolog">
    <arguments>
        <argument name="name" xsi:type="string">custom</argument>
    </arguments>
</virtualType>

Exam Tip: Virtual types are preferred over preference.

Important Concepts

  • Magento uses constructor-based DI
  • ObjectManager handles everything internally
  • di.xml configures dependencies
  • Preference overrides class
  • Virtual type modifies behavior safely

Practice MCQs

  1. What is DI?

    A) Database Integration
    B) Dependency Injection ✅
    C) Data Interface
    D) Dynamic Injection
  2. Which class manages object creation?

    A) Controller
    B) Object Manager ✅
    C) Block
    D) Model
  3. Which file configures DI?

    A) routes.xml
    B) module.xml
    C) di.xml ✅
    D) env.php
  4. Which method injects dependencies?

    A) setData()
    B) constructor ✅
    C) init()
    D) create()
  5. Which is used to override class?

    A) plugin
    B) observer
    C) preference ✅
    D) layout

Scenario-Based Questions

Q1: You need to replace core class behavior. What will you use?

Answer: Preference

Q2: You want to modify behavior without overriding class. What will you use?

Answer: Virtual Type

Q3: Developer used ObjectManager directly. Is it correct?

Answer: No (bad practice)

Q4: Dependency not injected properly. What could be wrong?

Answer: Missing constructor or wrong type hint

Practical Assignment 🔥

Create a custom module using DI:

  1. Create class Test
  2. Inject dependency via constructor
  3. Pass argument using di.xml
  4. Print value in template

Bonus: Create custom logger using virtual type

Module 7: Plugins & Observers in Magento 2

Subtitle: Modify behavior using Interceptors (Plugins) and Event Observers

Magento Event System

Magento allows extending functionality without modifying core code using:

  • Plugins (Interceptors)
  • Observers (Events)

Exam Tip: Always prefer Plugins over Preferences.

Plugins (Interceptors)

Plugins allow you to modify behavior of public methods in a class.

Types of Plugins:

  • Before → runs before method
  • After → runs after method
  • Around → wraps entire method

Plugin Example

di.xml


<type name="Magento\Catalog\Model\Product">
    <plugin name="custom_plugin"
            type="Vendor\Module\Plugin\ProductPlugin"/>
</type>

Plugin Class


class ProductPlugin
{
    public function beforeSave($subject)
    {
        // logic before save
    }

    public function afterSave($subject, $result)
    {
        return $result;
    }

    public function aroundSave($subject, $proceed)
    {
        // before
        $result = $proceed();
        // after
        return $result;
    }
}

Exam Tip: around plugin must call $proceed()

Observers (Events)

Observers listen to Magento events and execute custom logic.

Flow:

Event → Observer → Custom Logic

Observer Example

events.xml


<event name="checkout_submit_all_after">
    <observer name="custom_observer"
              instance="Vendor\Module\Observer\OrderPlace"/>
</event>

Observer Class


class OrderPlace implements \Magento\Framework\Event\ObserverInterface
{
    public function execute(
        \Magento\Framework\Event\Observer $observer
    ) {
        $order = $observer->getEvent()->getOrder();
    }
}

Exam Tip: Observers depend on event dispatch.

Plugin vs Observer

Feature Plugin Observer
Based On Method interception Event system
Control High Medium
Use Case Modify method behavior React to events
Execution Always runs Runs only if event triggered

Plugin Limitations

  • Cannot intercept private methods
  • Cannot intercept final methods
  • Cannot intercept constructors

Important Concepts

  • Plugin = method level control
  • Observer = event-based execution
  • Around plugin controls full execution
  • Use plugin for precise customization

Practice MCQs

  1. Which modifies method behavior?

    A) Observer
    B) Plugin ✅
    C) Controller
    D) Layout
  2. Which plugin type wraps method?

    A) before
    B) after
    C) around ✅
    D) wrap
  3. Which file defines observers?

    A) di.xml
    B) events.xml ✅
    C) module.xml
    D) routes.xml
  4. Can plugin modify private method?

    A) Yes
    B) No ✅
  5. Which depends on event dispatch?

    A) Plugin
    B) Observer ✅

Scenario-Based Questions

Q1: You want to modify product save logic. What will you use?

Answer: Plugin

Q2: You want to execute logic after order placed. What will you use?

Answer: Observer (checkout_submit_all_after)

Q3: You want full control over method execution. What will you use?

Answer: Around Plugin

Q4: Event not triggering observer. What could be wrong?

Answer: Wrong event name or events.xml location

Practical Assignment 🔥

Create both Plugin and Observer:

  1. Create plugin on Product save
  2. Log message before save
  3. Create observer on order place
  4. Fetch order data

Bonus: Compare execution order of multiple plugins

Module 8: Web APIs in Magento 2 (REST & GraphQL)

Subtitle: Learn how to expose and consume APIs in Magento

What are Web APIs?

Web APIs allow external systems (mobile apps, frontend apps, third-party services) to interact with Magento.

  • REST API (traditional)
  • GraphQL API (modern)

Exam Tip: Magento supports both REST and GraphQL.

REST API

REST (Representational State Transfer) is based on HTTP methods.

HTTP Methods:

  • GET → Fetch data
  • POST → Create data
  • PUT → Update data
  • DELETE → Remove data

Example:


GET /rest/V1/products

Exam Tip: REST uses URL-based endpoints.

Creating Custom REST API

Step 1: webapi.xml


<route url="/V1/custom/product" method="GET">
    <service class="Vendor\Module\Api\ProductInterface" method="getData"/>
    <resources>
        <resource ref="anonymous"/>
    </resources>
</route>

Step 2: Interface


namespace Vendor\Module\Api;

interface ProductInterface
{
    public function getData();
}

Step 3: Model Implementation


class Product implements ProductInterface
{
    public function getData()
    {
        return "Hello API";
    }
}

Authentication

  • Admin Token
  • Customer Token
  • Integration Token

Exam Tip: Token-based authentication is used in REST.

GraphQL API

GraphQL allows fetching only required data in a single request.

Example Query:


{
  products(search: "shirt") {
    items {
      name
      price {
        regularPrice {
          amount {
            value
          }
        }
      }
    }
  }
}

Exam Tip: GraphQL reduces over-fetching.

Create Custom GraphQL API

Step 1: schema.graphqls


type Query {
    customMessage: String @resolver(class: "Vendor\\Module\\Model\\Resolver\\Custom")
}

Step 2: Resolver


class Custom implements ResolverInterface
{
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        return "Hello GraphQL";
    }
}

REST vs GraphQL

Feature REST GraphQL
Data Fetch Fixed Flexible ✅
Endpoints Multiple Single
Performance Less efficient More efficient ✅
Usage Traditional Headless/PWA

Important Concepts

  • REST uses HTTP methods
  • GraphQL uses query language
  • webapi.xml defines REST endpoints
  • schema.graphqls defines GraphQL structure

Practice MCQs

  1. Which API uses single endpoint?

    A) REST
    B) GraphQL ✅
  2. Which file defines REST API?

    A) schema.graphqls
    B) webapi.xml ✅
  3. Which HTTP method fetches data?

    A) POST
    B) GET ✅
  4. GraphQL reduces what?

    A) Security
    B) Over-fetching ✅
  5. Which uses resolver?

    A) REST
    B) GraphQL ✅

Scenario-Based Questions

Q1: You want to expose custom API endpoint. What will you use?

Answer: webapi.xml

Q2: You want flexible data response for frontend app. What will you use?

Answer: GraphQL

Q3: API not working. What could be wrong?

Answer: Wrong route or authentication issue

Q4: You want to fetch product data with minimal response. What will you use?

Answer: GraphQL

Practical Assignment 🔥

Create both REST and GraphQL APIs:

  1. Create custom REST API
  2. Test using Postman
  3. Create GraphQL resolver
  4. Test in GraphQL playground

Bonus: Return product data dynamically

Module 9: Indexing & Cache in Magento 2

Subtitle: Understand performance optimization using Indexers and Cache

Why Indexing & Cache?

Magento uses indexing and caching to improve performance and reduce database load.

  • Indexing: Pre-process data for fast access
  • Cache: Store ready output to avoid re-processing

Exam Tip: Indexing improves query performance, cache improves page load speed.

Indexers

Indexers transform data into optimized format for frontend usage.

Common Indexers:

  • catalog_product_price
  • cataloginventory_stock
  • catalog_category_product
  • catalogsearch_fulltext

Example: Product price is pre-calculated and stored for fast retrieval.

Indexing Modes

  • Update on Save: Reindex immediately
  • Update by Schedule: Reindex via cron

Exam Tip: Schedule mode is better for performance.

Reindex Commands


php bin/magento indexer:reindex
php bin/magento indexer:status
php bin/magento indexer:set-mode schedule

Important: Reindex required after product or price changes.

Custom Indexer

You can create custom indexers for your module.

indexer.xml


<indexer id="custom_indexer" view_id="custom_indexer">
    <title>Custom Indexer</title>
</indexer>

Exam Tip: Used for large data processing.

Cache Types

Magento has multiple cache types:

  • Configuration
  • Layout
  • Block HTML
  • Full Page Cache (FPC)

Exam Tip: FPC gives biggest performance boost.

Cache Commands


php bin/magento cache:enable
php bin/magento cache:disable
php bin/magento cache:flush
php bin/magento cache:clean

Difference:

  • clean: Clears specific cache
  • flush: Clears all cache storage

Full Page Cache (FPC)

FPC stores entire page HTML for faster loading.

  • Built-in (file system)
  • Varnish (recommended)

Exam Tip: Varnish is preferred in production.

Important Concepts

  • Indexers optimize database queries
  • Cache improves response time
  • Reindex required after data changes
  • FPC stores full HTML output

Practice MCQs

  1. What improves query performance?

    A) Cache
    B) Indexing ✅
  2. Best indexing mode for production?

    A) Update on Save
    B) Schedule ✅
  3. Which gives highest performance boost?

    A) Layout Cache
    B) FPC ✅
  4. Difference between cache clean and flush?

    A) Same
    B) Different ✅
  5. Which command checks index status?

    A) indexer:status ✅

Scenario-Based Questions

Q1: Product price not updated on frontend. What will you do?

Answer: Reindex catalog_product_price

Q2: Website is slow. What should you check?

Answer: Cache + FPC + Indexers

Q3: Changes not visible after update. What will you do?

Answer: Cache clean/flush

Q4: Large catalog site. Which mode is best?

Answer: Schedule

Practical Assignment 🔥

Practice performance optimization:

  1. Change indexer mode to schedule
  2. Run reindex manually
  3. Enable all cache types
  4. Test page speed before/after

Bonus: Setup Varnish cache

Module 10: Deployment & Modes in Magento 2

Subtitle: Learn developer, production, and default modes with deployment process

What are Magento Modes?

Magento runs in different modes to control error reporting, performance, and deployment behavior.

  • Developer Mode
  • Production Mode
  • Default Mode

Exam Tip: Mode affects caching, error display, and static content.

Developer Mode

  • Shows detailed errors
  • No static content deployment required
  • Used during development

Command:


php bin/magento deploy:mode:set developer

Use Case: Local development

Production Mode

  • High performance
  • Errors are hidden
  • Requires static content deployment

Command:


php bin/magento deploy:mode:set production

Exam Tip: Always use production mode on live site.

Default Mode

  • Basic mode (not recommended)
  • Used for testing

Check Current Mode


php bin/magento deploy:mode:show

Deployment Steps

Typical production deployment flow:

  1. Pull latest code
  2. Run composer install
  3. Run setup upgrade
  4. Deploy static content
  5. Compile DI
  6. Flush cache

Commands:


php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy -f
php bin/magento cache:flush

Static Content Deployment

Generates CSS, JS, and frontend assets.


php bin/magento setup:static-content:deploy -f

Exam Tip: Required in production mode.

Important Concepts

  • Developer mode shows errors
  • Production mode optimized for performance
  • Static content required in production
  • DI compile improves performance

Practice MCQs

  1. Which mode shows errors?

    A) Production
    B) Developer ✅
  2. Best mode for live site?

    A) Default
    B) Developer
    C) Production ✅
  3. Which command compiles DI?

    A) setup:compile
    B) setup:di:compile ✅
  4. Static content required in?

    A) Developer
    B) Production ✅
  5. Which command shows mode?

    A) deploy:mode:show ✅

Scenario-Based Questions

Q1: Error not visible on production. Why?

Answer: Production mode hides errors

Q2: CSS not loading in production. What to do?

Answer: Run static content deploy

Q3: Website slow after deployment. What to check?

Answer: DI compile + cache + mode

Q4: Developer wants to debug issue. Which mode?

Answer: Developer mode

Practical Assignment 🔥

Perform full deployment:

  1. Switch to developer mode
  2. Make code changes
  3. Switch to production mode
  4. Run deployment commands
  5. Verify frontend

Bonus: Deploy Magento on VPS