Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 42 ยท Projects

Project: A Complete Custom Module

Assemble a full Magento 2.4 module end to end: declarative schema, repository, admin configuration, a frontend block and layout, with runnable plain-PHP stand-ins for each part.

You have learned the pieces one at a time: modules, dependency injection, schema, repositories, configuration, layouts and templates. This project puts them together in one small but complete module, Acme_Testimonials. It stores customer testimonials in its own database table, exposes them through a repository, lets the store owner switch the feature on and choose how many to show, and renders the approved ones on the home page.

Magento itself cannot run on this site, so the real module files are shown read-only, in the order you would create them. After each stage a runnable plain-PHP stand-in reproduces the behaviour with SQLite, a config reader and a template renderer, so you can see the data flow. The stand-ins are simplified teaching versions, not Magento code. Keep earlier lessons at hand: Your First Module, Declarative Schema, Service Contracts and Repositories, System Configuration and Layout XML and Handles.

The plan

flowchart LR
    A["db_schema.xml<br/>acme_testimonial table"] --> B["Model, ResourceModel<br/>and Collection"]
    B --> C["Repository<br/>(service contract)"]
    D["system.xml<br/>enabled and limit"] --> E["Block"]
    C --> E
    E --> F["Template and layout<br/>on the home page"]

Data flows from the table through the repository into a block that respects the admin settings, and layout XML places the block on a page.

The folder layout, under app/code/Acme/Testimonials/:

TEXT
registration.php
composer.json
etc/
  module.xml
  di.xml
  db_schema.xml
  db_schema_whitelist.json      (generated)
  config.xml
  acl.xml
  adminhtml/system.xml
Api/
  TestimonialRepositoryInterface.php
  Data/TestimonialInterface.php
Model/
  Testimonial.php
  ResourceModel/Testimonial.php
  ResourceModel/Testimonial/Collection.php
  TestimonialRepository.php
Block/Testimonials.php
view/frontend/
  layout/cms_index_index.xml
  templates/testimonials.phtml

Step 1: register the module

Two files make Magento see the module. See Your First Module if they look unfamiliar.

PHP
<?php
// registration.php
use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Acme_Testimonials', __DIR__);
XML
<!-- etc/module.xml -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Acme_Testimonials"/>
</config>

Then enable it with bin/magento module:enable Acme_Testimonials and run bin/magento setup:upgrade.

Step 2: the table

The table is declared, not scripted, in etc/db_schema.xml:

XML
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
    <table name="acme_testimonial" resource="default" engine="innodb" comment="Customer testimonials">
        <column xsi:type="int" name="testimonial_id" unsigned="true" nullable="false" identity="true" comment="ID"/>
        <column xsi:type="varchar" name="author" nullable="false" length="128" comment="Author name"/>
        <column xsi:type="text" name="body" nullable="false" comment="Testimonial text"/>
        <column xsi:type="smallint" name="is_approved" unsigned="true" nullable="false" default="0" comment="Approved flag"/>
        <constraint xsi:type="primary" referenceId="PRIMARY">
            <column name="testimonial_id"/>
        </constraint>
        <index referenceId="ACME_TESTIMONIAL_IS_APPROVED" indexType="btree">
            <column name="is_approved"/>
        </index>
    </table>
</schema>

Generate the whitelist file with bin/magento setup:db-declaration:generate-whitelist --module-name=Acme_Testimonials and commit it. The index matters: the storefront query filters on is_approved.

Step 3: model, resource model, collection and repository

The classic trio maps one table to PHP, which Models, Resource Models and Collections explains:

PHP
<?php
namespace Acme\Testimonials\Model;

use Magento\Framework\Model\AbstractModel;

class Testimonial extends AbstractModel
{
    protected function _construct(): void
    {
        $this->_init(ResourceModel\Testimonial::class);
    }
}
PHP
<?php
namespace Acme\Testimonials\Model\ResourceModel;

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

class Testimonial extends AbstractDb
{
    protected function _construct(): void
    {
        $this->_init('acme_testimonial', 'testimonial_id');
    }
}

The collection class extends Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection and its _construct() calls _init(Model\Testimonial::class, ResourceModel\Testimonial::class). Other code does not use these directly. It depends on the interface Api\TestimonialRepositoryInterface, with methods like save(), getById() and getApproved(int $limit), and di.xml binds the interface to the implementation:

XML
<!-- etc/di.xml -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Acme\Testimonials\Api\TestimonialRepositoryInterface"
                type="Acme\Testimonials\Model\TestimonialRepository"/>
</config>

The repository's getApproved() creates a collection, calls addFieldToFilter('is_approved', 1), sets the page size and returns the items. Validation (an author and a body are required) belongs in save(), so every caller gets it.

The first stand-in builds the same table in SQLite and a repository with validation and the approved-only query.

PHP Schema and repository on SQLite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Step 4: admin configuration

The store owner needs a switch and a number. etc/adminhtml/system.xml creates the fields, etc/config.xml supplies defaults, and etc/acl.xml defines the permission that guards the section. See System Configuration and Admin Controllers, Menus and ACL.

XML
<!-- etc/adminhtml/system.xml -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <section id="acme_testimonials" translate="label" type="text" sortOrder="900"
                 showInDefault="1" showInWebsite="1" showInStore="1">
            <label>Testimonials</label>
            <tab>general</tab>
            <resource>Acme_Testimonials::config</resource>
            <group id="display" translate="label" type="text" sortOrder="10"
                   showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Display</label>
                <field id="enabled" translate="label" type="select" sortOrder="10"
                       showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Show on home page</label>
                    <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                </field>
                <field id="limit" translate="label" type="text" sortOrder="20"
                       showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>How many to show</label>
                    <validate>validate-digits validate-greater-than-zero</validate>
                </field>
            </group>
        </section>
    </system>
</config>
XML
<!-- etc/config.xml -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default>
        <acme_testimonials>
            <display>
                <enabled>1</enabled>
                <limit>3</limit>
            </display>
        </acme_testimonials>
    </default>
</config>

Config values are read by path: acme_testimonials/display/limit.

Step 5: the block, layout and template

The block asks ScopeConfigInterface for the settings and the repository for the data. It never builds SQL:

PHP
<?php
namespace Acme\Testimonials\Block;

use Acme\Testimonials\Api\TestimonialRepositoryInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Store\Model\ScopeInterface;

class Testimonials extends Template
{
    public function __construct(
        Context $context,
        private readonly TestimonialRepositoryInterface $repository,
        private readonly ScopeConfigInterface $scopeConfig,
        array $data = []
    ) {
        parent::__construct($context, $data);
    }

    public function isEnabled(): bool
    {
        return $this->scopeConfig->isSetFlag('acme_testimonials/display/enabled', ScopeInterface::SCOPE_STORE);
    }

    public function getTestimonials(): array
    {
        $limit = (int) $this->scopeConfig->getValue('acme_testimonials/display/limit', ScopeInterface::SCOPE_STORE);

        return $this->repository->getApproved(max(1, $limit));
    }
}

A layout file for the home page handle puts the block into a container, as described in Layout XML and Handles:

XML
<!-- view/frontend/layout/cms_index_index.xml -->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Acme\Testimonials\Block\Testimonials" name="acme.testimonials"
                   template="Acme_Testimonials::testimonials.phtml"/>
        </referenceContainer>
    </body>
</page>
PHP
<?php /** @var \Acme\Testimonials\Block\Testimonials $block */ /** @var \Magento\Framework\Escaper $escaper */ ?>
<?php if ($block->isEnabled()): ?>
    <section class="acme-testimonials">
        <h2><?= $escaper->escapeHtml(__('What customers say')) ?></h2>
        <?php foreach ($block->getTestimonials() as $item): ?>
            <blockquote>
                <p><?= $escaper->escapeHtml($item->getBody()) ?></p>
                <footer><?= $escaper->escapeHtml($item->getAuthor()) ?></footer>
            </blockquote>
        <?php endforeach; ?>
    </section>
<?php endif; ?>

Every user-supplied value goes through the escaper, as the Performance and Security lesson recommends. A testimonial that contains <script> is harmless on the page.

Because the block lists database content on a cacheable page, a production version would also implement IdentityInterface and clean its cache tag after a save, as covered in Indexers and Caching.

The whole flow in a stand-in

The second stand-in wires the stages together in the order Magento does: layout says which block goes where, the block reads configuration and repository data, and the template renders with escaping. Config comes from three layers (module default, website scope, store view scope), so the same module shows different output per store view.

PHP Config, repository, block and template together

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read the output once more: the unapproved testimonial never appears, the script tag is escaped, the German store view shows three items while the default shows two, and the store view with the feature disabled renders nothing. Those four behaviours correspond to the approval filter in the repository, the escaper in the template, the scoped configuration, and the isEnabled() check.

Where to take it next

A production-grade module would add an admin grid to approve entries (a UI component listing, see UI Components Overview), a REST endpoint built from the same repository (The REST API), a unit test for the repository and block (Testing Magento Code), and cache identities on the block. Each of those reuses the same service contract, which is the main reason to design the repository first.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which file declares the acme_testimonial table in a modern Magento module?

    Declarative schema lives in etc/db_schema.xml. A generated db_schema_whitelist.json accompanies it.
  2. 2. Why does the block depend on the repository interface instead of the collection?

    A service contract keeps callers independent of how data is stored and gives you one place for validation and filtering.
  3. 3. Where do the default values for admin settings come from?

    system.xml defines the fields, and config.xml supplies the default values read through ScopeConfigInterface.
  4. 4. A testimonial contains a script tag. What protects visitors?

    Output escaping turns markup into harmless text. It is applied at output time for every value that can contain user input.

Summary

  • A complete module is built in layers: registration, declarative schema, model and resource model, repository bound by di.xml, admin configuration, block, layout and template.
  • Other code talks to the repository interface; the repository owns validation and the approved-only query.
  • Configuration is defined in system.xml, defaulted in config.xml, and read by path with a scope.
  • Layout XML decides where a block appears, and the template must escape every user-controlled value.
  • The same repository can later power an admin grid, a REST endpoint, tests and cache tags.

Next: Project: Extending Products with a Custom Attribute