Magento 2 is a powerful and flexible e-commerce platform that allows developers to create highly customizable online stores. This tutorial will guide you through the basics of Magento 2 development, including setting up a development environment, creating a custom module, and understanding the Magento 2 architecture.
1. Setting Up Your Development Environment
Before you start developing in Magento 2, you need to set up a proper development environment.
Prerequisites
- PHP: Magento 2 requires PHP 7.3 or later.
- Composer: Magento 2 uses Composer for dependency management.
- MySQL: Magento 2 requires MySQL 5.6 or later.
- Web Server: Apache or Nginx.
- Git: For version control.
Installation Steps
Install Magento 2 via Composer:
composer create-project --repository-url=https://repo.magento.com/ magento/project-community-edition magento2
Set Up the Database:
Create a new MySQL database and user for Magento 2.
Run the Magento Installation:
php bin/magento setup:install \
--base-url=http://yourdomain.com \
--db-host=localhost \
--db-name=magento2 \
--db-user=root \
--db-password=yourpassword \
--admin-firstname=Admin \
--admin-lastname=User \
[email protected] \
--admin-user=admin \
--admin-password=admin123 \
--language=en_US \
--currency=USD \
--timezone=America/Chicago \
--use-rewrites=1
Set Permissions:
Ensure that the var
, pub/static
, and app/etc
directories are writable.
Run the Magento CLI:
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy
2. Understanding Magento 2 Architecture
Magento 2 follows a modular architecture, which makes it highly extensible. Key components include:
- Modules: The building blocks of Magento 2. Each module contains code for a specific feature.
- Themes: Control the look and feel of the store.
- Layouts: Define the structure of the page.
- Templates: Contain the HTML and PHP code for rendering the page.
- Blocks: PHP classes that handle the business logic for rendering templates.
- Controllers: Handle user requests and return responses.
Read more about Magento Architecture here
3. Creating a Custom Module
Creating a simple custom module named Vendor_Module
.
Create the Module Directory Structure
Create the following directory structure:
app/code/Vendor/Module/ ├── etc/ │ ├── module.xml │ └── registration.php ├── registration.php └── composer.json
Enable the Module
Run the following commands to enable the module:
php bin/magento setup:upgrade
php bin/magento setup:di:compile
Read more about custom modules here
4. Working with Layouts and Templates
Step 1: Create a Layout File
Create a layout file at app/code/Vendor/Module/view/frontend/layout/vendor_module_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="Vendor\Module\Block\Hello" name="vendor_module_hello" template="Vendor_Module::hello.phtml"/>
</referenceContainer>
</body>
</page>
Step 2: Create a Block
Create a block at app/code/Vendor/Module/Block/Hello.php
:
<?php
namespace Vendor\Module\Block;
class Hello extends \Magento\Framework\View\Element\Template
{
public function getHelloMessage()
{
return 'Hello, Magento 2!';
}
}
Step 3: Create a Template
Create a template file at app/code/Vendor/Module/view/frontend/templates/hello.phtml
:
<h1><?php echo $block->getHelloMessage(); ?></h1>
5. Using Dependency Injection
Magento 2 uses Dependency Injection (DI) to manage object dependencies. Let’s create a simple service.
Step 1: Create a Service Interface
Create an interface at app/code/Vendor/Module/Api/GreeterInterface.php
:
<?php
namespace Vendor\Module\Api;
interface GreeterInterface
{
public function greet($name);
}
Step 2: Create a Service Implementation
Create a service implementation at app/code/Vendor/Module/Model/Greeter.php
:
<?php
namespace Vendor\Module\Model;
use Vendor\Module\Api\GreeterInterface;
class Greeter implements GreeterInterface
{
public function greet($name)
{
return "Hello, $name!";
}
}
Step 3: Use the Service in a Block
Modify the Hello
block to use the service:
<?php
namespace Vendor\Module\Block;
use Vendor\Module\Api\GreeterInterface;
class Hello extends \Magento\Framework\View\Element\Template
{
protected $greeter;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
GreeterInterface $greeter,
array $data = []
) {
$this->greeter = $greeter;
parent::__construct($context, $data);
}
public function getHelloMessage()
{
return $this->greeter->greet('Magento 2');
}
}
6. Creating a Custom Controller
Step 1: Create a Controller
Create a controller at app/code/Vendor/Module/Controller/Index/Index.php
:
<?php
namespace Vendor\Module\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action
{
protected $resultPageFactory;
public function __construct(
Context $context,
PageFactory $resultPageFactory
) {
$this->resultPageFactory = $resultPageFactory;
parent::__construct($context);
}
public function execute()
{
return $this->resultPageFactory->create();
}
}
Step 2: Define Routes
Create a routes file at app/code/Vendor/Module/etc/frontend/routes.xml
:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route id="vendor_module" frontName="vendor_module">
<module name="Vendor_Module"/>
</route>
</router>
</config>
7. Working with Databases
Step 1: Create a Model
Create a model at app/code/Vendor/Module/Model/Example.php
:
<?php
namespace Vendor\Module\Model;
use Magento\Framework\Model\AbstractModel;
class Example extends AbstractModel
{
protected function _construct()
{
$this->_init('Vendor\Module\Model\ResourceModel\Example');
}
}
Step 2: Create a Resource Model
Create a resource model at app/code/Vendor/Module/Model/ResourceModel/Example.php
:
<?php
namespace Vendor\Module\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Example extends AbstractDb
{
protected function _construct()
{
$this->_init('vendor_module_example', 'example_id');
}
}
Step 3: Create a Setup Script
Create a setup script at app/code/Vendor/Module/Setup/InstallSchema.php
:
<?php
namespace Vendor\Module\Setup;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Ddl\Table;
class InstallSchema implements InstallSchemaInterface
{
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$installer = $setup;
$installer->startSetup();
$table = $installer->getConnection()->newTable(
$installer->getTable('vendor_module_example')
)->addColumn(
'example_id',
Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Example ID'
)->addColumn(
'name',
Table::TYPE_TEXT,
255,
['nullable' => false],
'Name'
)->setComment(
'Example Table'
);
$installer->getConnection()->createTable($table);
$installer->endSetup();
}
}
8. Testing Your Module
Step 1: Write Unit Tests
Create a unit test at app/code/Vendor/Module/Test/Unit/Model/GreeterTest.php
:
<?php
namespace Vendor\Module\Test\Unit\Model;
use PHPUnit\Framework\TestCase;
use Vendor\Module\Model\Greeter;
class GreeterTest extends TestCase
{
public function testGreet()
{
$greeter = new Greeter();
$this->assertEquals('Hello, Magento 2!', $greeter->greet('Magento 2'));
}
}
Step 2: Run Tests
Run the tests using PHPUnit:
vendor/bin/phpunit app/code/Vendor/Module/Test/Unit/Model/GreeterTest.php
9. Deploying Your Module
Step 1: Package the Module
Create a composer.json
file for your module and package it:
composer archive --dir=dist --file=vendor-module-1.0.0.zip
Step 2: Install the Module
Install the module on your production server using Composer:
composer require vendor/module:1.0.0
Step 3: Enable the Module
Run the following commands to enable the module:
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy
Conclusion
This tutorial covered the basics of Magento 2 development, including setting up a development environment, creating a custom module, working with layouts and templates, using dependency injection, creating controllers, working with databases, testing, and deploying your module. With this foundation, you can start building more complex and powerful Magento 2 extensions.