Learn how to use Chat GPT as Magento 2 developer

Want to create Magento 2 modules quickly and efficiently? Discover how ChatGPT prompts can help you generate Magento 2 code with ease in this guide.

Picture for Learn how to use Chat GPT as Magento 2 developer
Picture by Matt Chad
Author's photo
Matt Chad
June 18, 2023

If you're a professional developer looking to create Magento 2 modules, you may be interested in using ChatGPT prompts to streamline the process. With these prompts, you can quickly generate code for your modules, saving time and effort. In this guide, we'll explore how ChatGPT prompts work and how they can benefit your Magento 2 development projects.

There is also a free plugin for PHPStorm - CodeGPT - which integrates IDE and OpenAi APIs. CodeGPT plugin for PHPStorm

What are GPT prompts?

GPT or more widely known as ChatGPT prompts are a type of artificial intelligence (AI) technology that can generate text based on a given prompt or topic. They use machine learning algorithms to analyze large amounts of data and generate responses that are similar to human language. In the context of Magento 2 development, ChatGPT prompts can be used to generate code for modules based on specific requirements or parameters. This can save developers time and effort, allowing them to focus on other aspects of their projects.

Issues with GPT

The use of GPT to generate code faces three main issues: lack of context, quality and reliability, and performance. To address these challenges, it is crucial to consider GPT-generated code as a starting point or reference rather than relying solely on it. Developers should thoroughly review, validate, and refine the generated code, ensuring it adheres to best practices, coding standards, and project-specific requirements. Incorporating manual review, testing, and peer code reviews into the development process can help overcome these challenges and ensure the final code meets the necessary quality and reliability standards.

Fortunately, GPT can also facilitate the generation of unit tests (PHPUnit) and performance tests (PHPBench) easily. This creates a unique meta-development experience where developers are not solely responsible for testing the code they write. Since AI lacks emotions, it can efficiently develop code and test it without encountering the same problems humans face. However, it remains the developer's responsibility to verify the final solution.

The primary advantage of using AI/ML for code development is conserving developers' energy. Just like a car can run out of fuel, developers can experience burnout or exhaustion. Code development can be mentally taxing and time-consuming, demanding concentration, problem-solving skills, and creativity. This is where AI/ML for code development comes into play.

Blue car on a desert road

Customizing and refining generated code for your specific needs

It's essential to approach code development as an iterative process, constantly evaluating and refining the code to align with evolving requirements. By customizing the generated code and leveraging tools such as PHPStan and PHPCSFixer, you can significantly improve the code's quality, maintainability, and adherence to coding standards. These tools enable you to enhance the code's suitability for your specific needs, ensuring it remains robust and up to industry standards.

List of Chat GPT prompts to increase your Magento 2 development speed

Here are some GPT prompts that can help speed up your Magento 2 development process. These prompts can also save your time by automating repetitive tasks and reducing the need for manual typing. Crafting code snippets can be a tedious and time-consuming task, and keeping them up-to-date can be a challenge.

Whether you are a beginner or an experienced developer, these GPT prompts can help increase your productivity and streamline your Magento 2 development workflow.

GPT prompt to reason about algorithm solution

Create a plan for {{BRIEF_ALGORITHM_DESCRIPTION}}.
Output optimal solutions.
Reason about mistakes in the plan.
Generate code using bash and tools available only for MacOS ARM64 according to the plan.

GPT prompt to step-by-step refactor

Modernize this PHP code to PHP 8.2 according to the following steps:
1. Replace constructor dependencies with constructor property promotion.
2. Add return types according to the PSR12 standard.
3. Add PHPDocs.
4. Format code according to the PSR12 standard.
{{selectedCode}}

GPT prompt to write PHPUnit tests

Here is the prompt for generating unit tests for Magento 2:

Use PHPUnit with no external testing libraries. 
Do not use stubs, use mocks instead. 
Use camelCase for naming. 
Do not explain code. 
Output only the code. 
Use PHP8.1 syntax.
Cover negative and positive paths. 
Write PHPUnit tests for the following code: {{selectedCode}}

This prompt should generate a clean PHPUnit test that:

  • covers positive and negative paths
  • output is the code only
  • sticks with PHP8.1 syntax
  • there are no code explanations nor comments

GPT prompt to create a new product attribute

Pick desired options from the square brackets:

Do not explain code. 
Output only the code. 
Use PHP8.1 syntax.
Add Magento 2 standard PHPDocs.
Create attribute install script for Magento 2.4 extension, where attribute has the following properties:
Attribute code: {{ATTRIBUTE_CODE}}
Attribute type: [boolean/int/decimal/text/varchar/date]
Attribute label: {{ATTRIBUTE_LABEL}}
Group: Content
Scope: [global/store/store_view]
Visible on catalog listing pages: [yes/no]
Display on the product page: [yes/no]
Filterable: [yes/no]
Searchable: [yes/no]
Apply to: [simple|configurable|bundle|virtual|downloadable]

Sample result:

<?php
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend;
use Magento\Catalog\Model\ResourceModel\Eav\Attribute as CatalogAttribute;

class InstallData implements \Magento\Framework\Setup\InstallDataInterface
{
    private $eavSetupFactory;

    public function __construct(\Magento\Eav\Setup\EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    public function install(\Magento\Framework\Setup\ModuleDataSetupInterface $setup, \Magento\Framework\Setup\ModuleContextInterface $context)
    {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'my_attribute',
            [
                'type' => 'int',
                'label' => 'My Attribute',
                'input' => 'boolean',
                'global' => ScopedAttributeInterface::SCOPE_GLOBAL,
                'visible' => true,
                'required' => false,
                'user_defined' => true,
                'default' => '',
                'group' => '',
                'backend' => '',
                'visible_on_front' => true,
                'used_in_product_listing' => true,
                'sort_order' => '',
                'searchable' => false,
                'filterable' => true,
                'comparable' => false,
                'visible_in_advanced_search' => false,
                'used_for_promo_rules' => false,
                'unique' => false,
                'apply_to' => '',
                'is_used_in_grid' => false,
                'is_visible_in_grid' => false,
                'is_filterable_in_grid' => false,
            ]
        );
    }
}

GPT prompt to create Magento 2 observer

Do not explain code. 
Output only the code. 
Use PHP8.1 syntax.
Add Magento 2 standard PHPDocs.
Create observer and event configuration for the product save event.

Generated observer class:

<?php
namespace Vendor\Module\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Catalog\Api\Data\ProductInterface;

class ProductSaveObserver implements ObserverInterface
{
    /**
     * @param Observer $observer
     * @return void
     */
    public function execute(Observer $observer): void
    {
        /** @var ProductInterface $product */
        $product = $observer->getEvent()->getData('product');
    }
}

Note how the first line can be used to generate file in the appropriate location:

<!-- app/code/Vendor/Module/etc/events.xml -->
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_product_save_after">
        <observer name="vendor_module_product_save_observer" instance="Vendor\Module\Observer\ProductSaveObserver" />
    </event>
</config>
Consulting avatar

Do you need assistance with your Magento 2 store?

Share this post