From d76a02f3364f5fe50c9e91edb91fb5ab93f512de Mon Sep 17 00:00:00 2001 From: David Lambauer Date: Tue, 1 Aug 2023 13:50:48 +0200 Subject: [PATCH] huuuuge wip --- README.md | 2 + acl-xml.md | 0 acl_xml.md | 100 ++ api-reference.md | 148 +++ basic-configuration.md | 205 ++-- best-practices-for-extension-development.md | 290 ++++++ best-practices-for-secure-development.md | 135 +++ brief-explanation-of-each-component.md | 117 +++ cache-management.md | 350 +++++++ cache-xml.md | 0 cache.md => cache_xml.md | 5 +- caching-in-magento-2.md | 0 ...studies-of-problem-solving-in-magento-2.md | 176 ++++ ci-cd.md | 0 cli-commands.md | 105 ++ ...nious-integration-continious-deployment.md | 129 +++ core-features.md | 17 +- cron-groups-xml.md | 0 cron-jobs-xml.md | 0 cron-jobs.md | 38 +- cron_groups_xml.md | 155 +++ cron_jobs.md => cron_jobs_xml.md | 4 +- css-preprocessing.md | 219 ++++ data-interfaces-and-models.md | 130 +++ database-access-and-orm.md | 188 ++++ db-schema-xml.md | 0 db_schema_xml.md | 126 +++ developing-extensions-in-magento-2.md | 240 +++++ di-xml.md | 0 di_xml.md | 105 ++ ...-to-visually-represent-the-architecture.md | 146 +++ directory-structure.md | 77 ++ documentation.md | 50 +- email-templates-xml.md | 0 email-templates.md | 185 ++++ email_templates.md => email_templates_xml.md | 4 +- events-xml.md | 0 events.md | 144 +++ events_xml.md | 101 ++ extension-attributes-xml.md | 0 extension-use-cases.md | 70 ++ extension_attributes.md | 142 +++ extension_attributes_xml.md | 90 ++ fieldset-xml.md | 0 fieldset_xml.md | 181 ++++ functional-testing.md | 112 +++ glossary-of-terms.md | 934 +++--------------- graphql-apis.md | 186 ++++ ...o-contribute-to-the-magento-2-community.md | 278 +++--- how-to-get-help-and-support.md | 110 +++ how-to-use-and-extend-apis.md | 292 ++++++ i18n.md | 84 ++ indexer-xml.md | 0 indexer_xml.md | 107 ++ indexers.md | 125 +++ installation-guide.md | 102 ++ integration-testing.md | 150 +++ javascript-in-magento-2.md | 192 ++++ javascript-testing.md | 182 ++++ knockoutjs-integration.md | 118 +++ layout-xml.md | 0 layout_xml.md | 117 +++ layouts-blocks-and-templates.md | 154 +++ logging.md | 124 +++ magento-2-coding-standards.md | 188 ++++ menu-xml.md | 0 menu_xml.md | 120 +++ module-development.md | 449 +++++++++ observers.md | 180 ++++ overview-of-magento-2-apis.md | 147 ++- overview-of-magento-2-development.md | 302 +++++- overview-of-magento-2.md | 138 +-- overview-of-the-architectural-components.md | 169 ++++ performance-best-practices.md | 186 ++++ performance-testing.md | 98 ++ plugins.md | 121 +++ recommended-development-workflows.md | 128 +++ reporting-security-issues.md | 80 ++ requirejs.md | 178 ++++ rest-apis-soap-apis.md | 136 +++ rest-apis.md | 207 ++++ routes-xml.md | 0 routes_xml.md | 96 ++ scalability-options-and-recommendations.md | 110 +++ search.md | 131 +++ security-features-in-magento-2.md | 162 +++ server-setup-and-configuration.md | 112 +++ service-contracts.md | 162 +++ soap-apis.md | 120 +++ static-testing.md | 109 ++ system-xml.md | 0 system_xml.md | 165 ++++ testing-tools.md | 161 +++ ...gento-application-and-service-contracts.md | 122 +++ the-magento-application.md | 168 ++++ theme-development.md | 206 ++++ troubleshooting-common-installation-issues.md | 112 +++ ui-components.md | 135 +++ unit-testing.md | 346 ++----- versions-and-updates.md | 106 ++ view-xml.md | 0 view_xml.md | 141 +++ web-api.md | 115 +++ webapi-xml.md | 0 webapi_xml.md | 98 ++ widget-xml.md | 0 widget_xml.md | 131 +++ widgets.md | 121 +++ working-with-adminhtml.md | 188 ++++ 109 files changed, 12203 insertions(+), 1482 deletions(-) delete mode 100644 acl-xml.md create mode 100644 acl_xml.md delete mode 100644 cache-xml.md rename cache.md => cache_xml.md (99%) delete mode 100644 caching-in-magento-2.md delete mode 100644 ci-cd.md create mode 100644 continious-integration-continious-deployment.md delete mode 100644 cron-groups-xml.md delete mode 100644 cron-jobs-xml.md create mode 100644 cron_groups_xml.md rename cron_jobs.md => cron_jobs_xml.md (98%) delete mode 100644 db-schema-xml.md create mode 100644 db_schema_xml.md delete mode 100644 di-xml.md create mode 100644 di_xml.md delete mode 100644 email-templates-xml.md rename email_templates.md => email_templates_xml.md (99%) delete mode 100644 events-xml.md create mode 100644 events_xml.md delete mode 100644 extension-attributes-xml.md create mode 100644 extension_attributes.md create mode 100644 extension_attributes_xml.md delete mode 100644 fieldset-xml.md create mode 100644 fieldset_xml.md delete mode 100644 indexer-xml.md create mode 100644 indexer_xml.md delete mode 100644 layout-xml.md create mode 100644 layout_xml.md delete mode 100644 menu-xml.md create mode 100644 menu_xml.md delete mode 100644 routes-xml.md create mode 100644 routes_xml.md delete mode 100644 system-xml.md create mode 100644 system_xml.md delete mode 100644 view-xml.md create mode 100644 view_xml.md delete mode 100644 webapi-xml.md create mode 100644 webapi_xml.md delete mode 100644 widget-xml.md create mode 100644 widget_xml.md diff --git a/README.md b/README.md index 77e8072..7cbbba5 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # Mage-OS Documentation +[TOC] + You can find the online version of the Mage-OS documentation at [https://devdocs.mage-os.org/](https://devdocs.mage-os.org) ## Markup and Features diff --git a/acl-xml.md b/acl-xml.md deleted file mode 100644 index e69de29..0000000 diff --git a/acl_xml.md b/acl_xml.md new file mode 100644 index 0000000..c9c53fc --- /dev/null +++ b/acl_xml.md @@ -0,0 +1,100 @@ +# `acl.xml` Reference Documentation + +[TOC] + +This reference documentation provides information on the structure and usage of the `acl.xml` file in Magento 2. +`acl.xml` is an essential configuration file used to define Access Control List (ACL) permissions for various +resources in your Magento 2 module or extension. + +## Introduction + +Access Control List (ACL) is a security mechanism used to control access to resources based on user roles and +permissions. The `acl.xml` file is used in Magento 2 to define these roles, resources, and associated permissions for +your module or extension. + +## Structure of `acl.xml` + +The `acl.xml` file follows a specific structure and should be placed in the `etc` directory of your module or extension. +Here is an example of the basic structure of `acl.xml`: + +```xml + + + + + +``` + +The `xmlns:xsi` and `xsi:noNamespaceSchemaLocation` attributes define the XML schema for validation. The `` tag is +the root element, under which you define resources and roles. + +## Defining Resources and Roles + +In the `` tag, you define `` and `` elements to specify the resources and roles respectively. A +resource represents a specific functionality or area in your module or extension, while a role represents a user role or +group. + +Here is an example of defining a resource and a role in `acl.xml`: + +```xml + + + + + + + + + + + + + + + +``` + +In the above example, the `` element defines a resource with an `id`, `title`, and `sortOrder`. The `id` +should follow the format `::`. Similarly, the `` element defines a role with +an `id`, `title`, and `sortOrder`. + +## Applying ACL Permissions + +Once you have defined resources and roles, you need to specify the permissions or access rules for each role on the +respective resources. For this, you use the `` and `` elements. + +Here is an example of applying ACL permissions in `acl.xml`: + +```xml + + + + + + + + + + + + + + + + + + + + + +``` + +In the above example, the `` element is nested under the appropriate `` and ``. The `id` +attribute follows the format `::`. The `title` attribute provides a human-readable +title for the permission. + +## Conclusion + +The `acl.xml` file is a crucial configuration file in Magento 2 for defining Access Control List (ACL) permissions. By +understanding its structure and usage, you can control access to resources based on user roles and permissions +effectively. diff --git a/api-reference.md b/api-reference.md index e69de29..8d60a00 100644 --- a/api-reference.md +++ b/api-reference.md @@ -0,0 +1,148 @@ +# API Reference Documentation + +[TOC] + +## Introduction + +Welcome to the API Reference Documentation for the Magento 2 API. This comprehensive guide will provide you with all the +necessary information to interact with the Magento 2 API programmatically using PHP. + +## Prerequisites + +Before you start using the Magento 2 API, make sure you have the following prerequisites: + +- Basic knowledge of PHP programming language +- Familiarity with Magento 2 architecture and concepts +- Access to a Magento 2 installation with API access enabled + +## API Basics + +Magento 2 provides a powerful API that allows you to interact with various aspects of the system, including customers, +products, orders, and more. The API is implemented using the Representational State Transfer (REST) architectural style +and is designed to be platform-agnostic. + +To authenticate and interact with the API, you need to obtain an access token, which acts as a credential to +authenticate your requests. You can obtain an access token by authenticating with the Magento 2 OAuth server using your +credentials. Once you have the access token, you can use it to make authorized requests to the API. + +## API Endpoints + +The Magento 2 API is organized into several endpoints, each representing a different aspect of the system. The endpoints +provide a set of resources and operations that you can use to manipulate and retrieve data. + +Here are some of the main API endpoints available in Magento 2: + +### Customers + +The Customers API endpoint allows you to manage customer-related information, such as creating new customers, retrieving +customer details, updating customer information, and more. + +```php +// Example: Retrieve customer details +GET /rest/V1/customers/{customerId} +``` + +### Products + +The Products API endpoint provides methods to manage product-related data, such as creating new products, retrieving +product information, updating product attributes, and more. + +```php +// Example: Create a new product +POST /rest/V1/products +``` + +### Orders + +The Orders API endpoint allows you to manage orders in Magento 2, including creating new orders, retrieving order +details, updating order status, and more. + +```php +// Example: Retrieve order details +GET /rest/V1/orders/{orderId} +``` + +### Carts + +The Carts API endpoint provides methods to manage shopping carts, including creating new carts, adding products to a +cart, retrieving cart details, and more. + +```php +// Example: Create a new cart +POST /rest/V1/carts/mine +``` + +## Making API Requests + +To make API requests, you can use any HTTP client library that supports sending HTTP requests. In PHP, you can use +libraries such as Guzzle, cURL, or the built-in `file_get_contents()` function. + +Here's an example of making a GET request to retrieve customer details using the Guzzle HTTP client library: + +```php +request('GET', 'https://example.com/rest/V1/customers/1', [ + 'headers' => [ + 'Authorization' => 'Bearer {access_token}', + 'Content-Type' => 'application/json', + ], +]); + +// Get the response body +$body = $response->getBody(); + +// Process the response data +$customer = json_decode($body, true); + +// Print the customer details +echo "Customer Name: " . $customer['firstname'] . " " . $customer['lastname']; +``` + +## Error Handling + +When interacting with the Magento 2 API, it's important to handle errors properly. The API returns meaningful error +messages and HTTP status codes to indicate the success or failure of a request. + +Here's an example of handling errors when retrieving customer details: + +```php +// Make a GET request to retrieve customer details +try { + $response = $client->request('GET', 'https://example.com/rest/V1/customers/1', [ + 'headers' => [ + 'Authorization' => 'Bearer {access_token}', + 'Content-Type' => 'application/json', + ], + ]); + + // Get the response body + $body = $response->getBody(); + + // Process the response data + $customer = json_decode($body, true); + + // Print the customer details + echo "Customer Name: " . $customer['firstname'] . " " . $customer['lastname']; +} catch (\GuzzleHttp\Exception\RequestException $e) { + // Handle request exceptions (e.g., connection errors, server errors, etc.) + echo "Request Exception: " . $e->getMessage(); +} catch (\Exception $e) { + // Handle other exceptions + echo "Exception: " . $e->getMessage(); +} +``` + +## Conclusion + +Congratulations! You now have a solid understanding of the Magento 2 API and how to interact with it using PHP. Refer to +the API documentation for further details on available endpoints, request/response formats, and additional +functionality. + +Happy coding! diff --git a/basic-configuration.md b/basic-configuration.md index cc15f98..ba66ec2 100644 --- a/basic-configuration.md +++ b/basic-configuration.md @@ -1,84 +1,121 @@ -# Basic Configuration in Magento 2 - -- [Global Configuration: env.php](#global-configuration-env.php) -- [Application Configuration: config.php](#application-configuration-config.php) -- [Module Configuration: config.xml](#module-configuration-config.xml) - -Magento 2, a highly flexible PHP-based e-commerce framework, provides a wealth of configuration options that allow you -to tailor your e-commerce platform precisely to your needs. This guide aims to provide you with a comprehensive -understanding of Magento 2's basic configuration. - -## Global Configuration: env.php - -Magento's global configuration is located in the `app/etc/env.php` file. This file contains settings that apply to the -entire Magento application, such as backend frontname, install date, crypt key, session save location, and more. - -### Example - -```php -return [ - 'backend' => - [ - 'frontName' => 'admin', - ], - 'install' => - [ - 'date' => 'Fri, 25 Jun 2023 19:25:14 +0000', - ], - // ... -]; -``` - -In the above example, `'frontName' => 'admin'`, is the URL segment for the admin panel. - -## Application Configuration: config.php - -Magento's `config.php` file is located in the same directory as `env.php` (`app/etc/`). This file is responsible for -managing the list of installed modules and their `enable/disable` status. - -```php -return [ - 'modules' => [ - 'Magento_Store' => 1, - 'Magento_AdminNotification' => 1, - //... - ], -]; -``` - -In this configuration, `'Magento_Store'` and `'Magento_AdminNotification'` modules are enabled as indicated by `'1'`. -If a module is disabled, it would be indicated by `'0'`. - -## Module Configuration: config.xml - -Each module in Magento 2 has its own `config.xml` file which is found in the `etc` directory of the respective module. -This file is used to manage module-specific configurations, such as default values for the module's settings. - -### Example - -Let's take a look at an example configuration in a `config.xml` file: - -```xml - - - - - - 12 - - - - -``` - -In this example, we have the `12` configuration inside the `` path. -This particular setting dictates the default number of products displayed per page on the product list. - -Remember: After modifying a module's `config.xml file`, it's necessary to clear Magento's cache (System > Tools > Cache -Management) to apply the changes. - -Before adjusting these configurations, remember that they can significantly impact your application's functionality and -behavior. It's highly recommended that you have a thorough understanding of Magento 2's architecture and always test -these changes in a development or staging environment before applying them to a live store. This ensures stability and -can prevent unintended effects on the end-user experience. +# Basic Configuration Documentation + +[TOC] + +This document provides instructions on how to perform basic configuration in Magento 2. Magento 2 is a powerful +e-commerce platform built on PHP, and understanding how to configure it is essential for creating a successful online +store. In this guide, we will cover the most important configuration settings and provide concrete examples and code +snippets to help you understand and implement them. + +## System Configuration + +The system configuration in Magento 2 allows you to set up and manage various aspects of your e-commerce store. + +To access the system configuration, follow these steps: + +1. Log in to the Magento 2 admin panel. +2. Navigate to **Stores** > **Configuration**. + +### Example: Changing the Base URL + +One of the most crucial system configuration settings is the Base URL. This setting determines the URL that customers +will use to access your store. + +To change the Base URL: + +1. Go to **Stores** > **Configuration**. +2. In the left-hand menu, click on **General** > **Web**. +3. Expand the **Base URLs (Secure)** or **Base URLs (Unsecure)** section, depending on your requirements. +4. Enter the desired URL in the **Base URL** field. +5. Click on **Save Config**. + +## Store Configuration + +Store configuration settings in Magento 2 allow you to customize various aspects related to your store's appearance and +functionality. + +To access the store configuration, follow these steps: + +1. Log in to the Magento 2 admin panel. +2. Navigate to **Stores** > **Configuration**. + +### Example: Changing the Store Name + +The store name is displayed prominently on your website and should reflect your brand and business. + +To change the store name: + +1. Go to **Stores** > **Configuration**. +2. In the left-hand menu, click on **General** > **Store Information**. +3. Enter the desired store name in the **Store Name** field. +4. Click on **Save Config**. + +## Catalog Configuration + +Catalog configuration settings in Magento 2 allow you to manage how your products are displayed, categorized, and +priced. + +To access the catalog configuration, follow these steps: + +1. Log in to the Magento 2 admin panel. +2. Navigate to **Stores** > **Configuration**. + +### Example: Setting Up Product Categories + +Product categories help customers navigate your store and find the products they are looking for. To set up product +categories: + +1. Go to **Stores** > **Configuration**. +2. In the left-hand menu, click on **Catalog** > **Catalog**. +3. Expand the **Category Top Navigation** section. +4. Enable the **Enable Category Top Navigation Menu** option. +5. Click on **Save Config**. + +## Payment Configuration + +Payment configuration settings in Magento 2 allow you to set up and manage the payment methods available to your +customers. + +To access the payment configuration, follow these steps: + +1. Log in to the Magento 2 admin panel. +2. Navigate to **Stores** > **Configuration**. + +### Example: Enabling PayPal Express Checkout + +PayPal Express Checkout is a popular payment method. To enable PayPal Express Checkout: + +1. Go to **Stores** > **Configuration**. +2. In the left-hand menu, click on **Sales** > **Payment Methods**. +3. Expand the **PayPal Express Checkout** section. +4. Set the **Enabled** option to **Yes**. +5. Enter your PayPal API credentials in the appropriate fields. +6. Click on **Save Config**. + +## Shipping Configuration + +Shipping configuration settings in Magento 2 allow you to manage how shipping is calculated and handled in your store. + +To access the shipping configuration, follow these steps: + +1. Log in to the Magento 2 admin panel. +2. Navigate to **Stores** > **Configuration**. + +### Example: Configuring Flat Rate Shipping + +Flat rate shipping charges a fixed rate for shipping regardless of the order's weight or location. To configure flat +rate shipping: + +1. Go to **Stores** > **Configuration**. +2. In the left-hand menu, click on **Sales** > **Shipping Methods**. +3. Expand the **Flat Rate** section. +4. Set the **Enabled** option to **Yes**. +5. Configure the **Title**, **Method Name**, **Price**, and other relevant fields. +6. Click on **Save Config**. + +## Conclusion + +In this documentation, we have covered the basic configuration settings in Magento 2, including system, store, catalog, +payment, and shipping configurations. By following the provided instructions and using the code snippets and examples, +you can easily configure your Magento 2 store to meet your specific requirements. For more advanced configuration +options, refer to the official Magento 2 documentation or consult with a Magento developer. diff --git a/best-practices-for-extension-development.md b/best-practices-for-extension-development.md index e69de29..7c63cbe 100644 --- a/best-practices-for-extension-development.md +++ b/best-practices-for-extension-development.md @@ -0,0 +1,290 @@ +# Best Practices for Extension Development + +[TOC] + +This documentation provides a comprehensive guide on best practices for developing extensions in Magento 2. Following +these guidelines will ensure that your extensions are efficient, secure, and compatible with future versions of Magento. + +## Directory Structure + +Organizing your extension's files properly is crucial for maintainability. Follow the recommended directory structure +provided by Magento to ensure consistency across projects. + +Here's a typical directory structure for a Magento 2 extension: + +``` +├── app +│ └── code +│ └── VendorName +│ └── ModuleName +│ ├── Block +│ ├── Controller +│ ├── etc +│ ├── Helper +│ ├── Model +│ ├── Observer +│ ├── Plugin +│ ├── Setup +│ ├── Ui +│ └── view +└── ... +``` + +## Extension Naming + +Choose a unique, descriptive name for your extension to avoid conflicts with other extensions. Magento recommends using +the following format for naming your extension: `VendorName_ModuleName`. + +For example, if your extension is related to a payment gateway named "FastPay" and your company name is "Acme", you +could name your extension `Acme_FastPay`. + +## Module Registration + +To register your extension with Magento, create a `registration.php` file in the root directory of your extension. This +file should contain a registration callback function that returns an array with the module's name and version. + +Here's an example of a `registration.php` file: + +```php + + +Magento 2 heavily utilizes dependency injection to manage object dependencies. Follow the dependency inversion principle +and inject dependencies through constructors or setter methods. + +Avoid instantiating objects directly using the `new` keyword within your extension. Instead, rely on Magento's +dependency injection framework to provide necessary dependencies. + +Here's an example of how to inject a dependency in a constructor: + +```php +gateway = $gateway; + } +} +``` + +## Event Observers + +Magento 2 provides a robust event system that allows extensions to observe and modify the behavior of the core system. +Leverage event observers to extend or customize Magento functionality. + +To create an event observer, you need to define the event you want to observe in your extension's `events.xml` file, and +then create a corresponding observer class. + +Here's an example of an `events.xml` file: + +```xml + + + + + + +``` + +And here's an example of an observer class: + +```php + + +Provide a user-friendly configuration interface for your extension using the `system.xml` file. This file defines the +configuration fields and sections that appear in the admin panel. + +Here's an example of a `system.xml` file: + +```xml + + + + + + +
+ + acme + Acme_FastPay::config + + + + + Magento\Config\Model\Config\Source\Yesno + + + +
+
+
+``` + +## Database Schema and Setup + +If your extension requires additional database tables or changes to existing tables, follow Magento's recommended +approach for managing database schema and setup. + +Create a `db_schema.xml` file to define your extension's database schema. Within this file, you can define tables, +columns, indexes, and other database elements. + +Here's an example of a `db_schema.xml` file: + +```xml + + + + + + + + + +
+
+``` + +To handle database setup and versioning, create an `InstallSchema.php` file in your extension's `Setup` directory. This +file should contain the necessary logic to create or update your extension's database schema. + +Here's an example of an `InstallSchema.php` file: + +```php +startSetup(); + + // Add database schema setup logic here + + $installer->endSetup(); + } +} +``` + +## Code Quality + +Writing clean and well-documented code is essential for maintainability and collaboration. Follow these best practices +to ensure high code quality: + +- Follow the [PSR-12 coding style](https://www.php-fig.org/psr/psr-12/) for PHP code. +- Use meaningful variable and function names to improve readability. +- Add inline comments to explain complex or important sections of code. +- Write PHPDoc comments for classes, methods, and properties to provide clear documentation. + +## Unit Testing + +Writing unit tests for your extension is crucial to ensure its stability and reliability. Magento provides a robust +testing framework based on PHPUnit. + +Create test classes for your extension using the `Test` directory structure. Test classes should be namespaced under the +extension's namespace with the `Test\Unit` suffix. + +Here's an example of a test class for a payment gateway extension: + +```php +objectManager = new ObjectManager($this); + + $this->payment = $this->objectManager->getObject( + Payment::class, + [ + // Inject dependencies here + ] + ); + } + + public function testExample() + { + // Write your unit tests here + } +} +``` + +## Security Considerations + +Ensure the security of your extension by following these best practices: + +- Validate and sanitize all user inputs to prevent security vulnerabilities such as SQL injection and cross-site + scripting. +- Use Magento's built-in security features, such as CSRF protection and form key validation, when handling sensitive + operations or user data. +- Regularly update your extension to address any security vulnerabilities discovered in dependencies or Magento itself. +- Stay informed about Magento's security practices and guidelines by regularly checking their official documentation and + security advisories. + +## Compatibility + +Maintaining compatibility with different versions of Magento is crucial for the longevity and adoption of your +extension. Follow these guidelines to ensure compatibility: + +- Keep up-to-date with Magento's latest releases and features to leverage new functionality. +- Avoid using deprecated Magento features or methods. +- Test your extension across different versions of Magento to identify and resolve compatibility issues. +- Clearly communicate the supported Magento versions in your extension's documentation and release notes. + +By adhering to these best practices, you can develop high-quality Magento 2 extensions that are secure, efficient, and +compatible across different versions of Magento. diff --git a/best-practices-for-secure-development.md b/best-practices-for-secure-development.md index e69de29..4520dbd 100644 --- a/best-practices-for-secure-development.md +++ b/best-practices-for-secure-development.md @@ -0,0 +1,135 @@ +# Best Practices for Secure Development + +[TOC] + +In today's digital landscape, security is of paramount importance. As a developer, it is essential to incorporate secure +practices into your development process to protect sensitive data and prevent unauthorized access to your applications. +This guide will outline best practices for secure development, specifically focusing on PHP and Magento 2. + +## Input Validation and Sanitization + +One common vulnerability in web applications is insufficient input validation and sanitization. Attackers can exploit +this weakness by injecting malicious code or performing various types of attacks such as SQL injection or cross-site +scripting (XSS). To mitigate these risks, always validate and sanitize user inputs before using them in your +application. + +### Example: Input Validation in PHP + +```php +$email = $_POST['email']; + +if (filter_var($email, FILTER_VALIDATE_EMAIL)) { + // Valid email address, proceed with further processing +} else { + // Invalid email address, handle the error appropriately +} +``` + +### Example: Input Sanitization in Magento 2 + +```php +$productId = $this->getRequest()->getParam('id'); + +$sanitizedProductId = $this->filterManager->sanitize($productId); +``` + +## Secure Authentication and Authorization + +Proper authentication and authorization mechanisms are crucial to prevent unauthorized access to sensitive data and +functionalities within your application. Always use strong and unique passwords, implement secure password storage using +hashing algorithms, and enforce multi-factor authentication where appropriate. Additionally, ensure that users are +authorized to access specific resources or perform certain actions based on their roles and privileges. + +### Example: Secure Password Storage in PHP + +```php +$password = $_POST['password']; + +$hashedPassword = password_hash($password, PASSWORD_DEFAULT); +``` + +### Example: Authorization in Magento 2 + +```php +if ($this->_authorization->isAllowed('Namespace_Module::resource')) { + // Authorized, proceed with the requested action +} else { + // Unauthorized, handle the error appropriately +} +``` + +## Protection against Cross-Site Scripting (XSS) Attacks + +Cross-Site Scripting (XSS) attacks occur when an attacker injects malicious scripts into web pages viewed by other +users. These scripts can then steal sensitive information, manipulate website content, or perform other malicious +activities. To prevent XSS attacks, always sanitize user-generated content and encode it properly when outputting it +into web pages. + +### Example: XSS Prevention in PHP + +```php +$userInput = $_POST['message']; + +$cleanInput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8'); +``` + +### Example: XSS Prevention in Magento 2 + +```php +$customerName = $this->escaper->escapeHtml($customer->getName()); +``` + +## Protection against SQL Injection Attacks + +SQL Injection attacks occur when an attacker injects malicious SQL statements into queries executed by an application's +database. This can lead to unauthorized access, data manipulation, or even complete data loss. To prevent SQL Injection +attacks, always use prepared statements or parameterized queries, and never concatenate user inputs directly into SQL +statements. + +### Example: SQL Injection Prevention in PHP + +```php +$userInput = $_POST['username']; + +$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username'); +$stmt->bindParam(':username', $userInput); +$stmt->execute(); +``` + +### Example: SQL Injection Prevention in Magento 2 + +```php +$userInput = $this->getRequest()->getParam('username'); + +$collection = $this->productCollectionFactory->create(); +$collection->addFieldToFilter('username', $userInput); +``` + +## Regular Security Updates and Patching + +Stay updated with the latest security patches and updates for your programming language, framework, and any external +libraries you use. These updates often include security fixes for known vulnerabilities. Regularly applying these +updates will help protect your application from potential security risks. + +## Secure Configuration and Sensitive Data Protection + +Ensure that sensitive configuration files, passwords, API keys, and other credentials are stored securely and not +accessible to unauthorized individuals. Avoid hardcoding sensitive information directly into your code and utilize +secure storage mechanisms such as environment variables or encrypted configuration files. + +## Implementing Secure Communication (HTTPS) + +Always use secure communication channels, such as HTTPS, to encrypt data transmission between clients and servers. This +prevents eavesdropping, tampering, and protects sensitive information from being intercepted by attackers. + +## Regular Security Audits and Penetration Testing + +Perform regular security audits and penetration testing on your applications to identify and fix any vulnerabilities. +Consider engaging third-party security professionals to conduct thorough security assessments and provide +recommendations for further improvements. + +## Conclusion + +By following these best practices for secure development, you can significantly reduce the risk of security breaches and +protect your applications and users' sensitive data. Remember to always stay updated with the latest security practices +and be proactive in addressing potential vulnerabilities. diff --git a/brief-explanation-of-each-component.md b/brief-explanation-of-each-component.md index e69de29..905d738 100644 --- a/brief-explanation-of-each-component.md +++ b/brief-explanation-of-each-component.md @@ -0,0 +1,117 @@ +# Component Documentation + +[TOC] + +This documentation provides a brief explanation of each component in the PHP and Magento 2 ecosystem. Each component +plays a crucial role in the development and functioning of a Magento 2 application. Familiarity with programming, +specifically PHP and Magento 2, is assumed. + +## Magento Framework Component + +The Magento Framework Component is the foundation of the Magento 2 application. It provides a modular architecture and a +set of libraries and interfaces that enable developers to create and extend Magento functionality. This component +includes the `Magento\Framework` namespace and is responsible for essential features such as dependency injection, event +management, configuration management, and more. + +Example of using the Magento Framework Component: + +```php +use Magento\Framework\App\Bootstrap; +require __DIR__ . '/app/bootstrap.php'; + +$bootstrap = Bootstrap::create(BP, $_SERVER); +$objectManager = $bootstrap->getObjectManager(); +``` + +## Magento Module Component + +The Magento Module Component is responsible for encapsulating specific areas of functionality within a Magento 2 +application. Each module corresponds to a functionality or feature and contains the necessary code, configurations, +layouts, and templates required to implement that feature. Modules are located in the `app/code` directory and follow +the `VendorName_ModuleName` naming convention. + +Example module structure: + +``` +app +├── code +│ └── VendorName +│ └── ModuleName +│ ├── Block +│ ├── Controller +│ ├── etc +│ ├── Model +│ ├── Setup +│ ├── view +│ └── web +└── ... +``` + +## Magento Theme Component + +The Magento Theme Component defines the visual appearance and layout of a Magento 2 storefront. It includes the +necessary files such as CSS, JavaScript, images, templates, and layouts to define the presentation layer. Themes are +located in the `app/design` directory and allow for customization and branding of the storefront. + +Example of a theme structure: + +``` +app +├── design +│ └── frontend +│ └── VendorName +│ └── theme +│ ├── etc +│ ├── Magento_Theme +│ ├── media +│ ├── web +│ └── registration.php +└── ... +``` + +## Magento Library Component + +The Magento Library Component provides a set of reusable libraries and functionality that can be used across multiple +Magento 2 applications. These libraries are located in the `lib` directory and are shared dependencies among different +modules and themes. + +Example of using a Magento library component: + +```php +use Magento\Framework\Filesystem\DirectoryList; + +class MyCustomClass +{ + protected $directoryList; + + public function __construct(DirectoryList $directoryList) + { + $this->directoryList = $directoryList; + } + + public function getPath() + { + return $this->directoryList->getRoot(); + } +} +``` + +## Magento CLI Component + +The Magento CLI (Command Line Interface) Component provides a command-line tool that allows developers to perform +various administrative and development tasks. It provides a convenient way to interact with the Magento 2 system, run +scripts, manage modules, and perform database operations. The CLI commands are located in the `bin/magento` file. + +Example of running a CLI command: + +```shell +php bin/magento cache:flush +``` + +## Conclusion + +Understanding the various components in the PHP and Magento 2 ecosystem is crucial for developing and maintaining +Magento 2 applications. The Magento Framework Component, Magento Module Component, Magento Theme Component, Magento +Library Component, and Magento CLI Component all contribute to the overall architecture and functionality of a Magento 2 +application. By utilizing these components effectively, developers can create powerful and customized e-commerce +solutions. diff --git a/cache-management.md b/cache-management.md index e69de29..35368a0 100644 --- a/cache-management.md +++ b/cache-management.md @@ -0,0 +1,350 @@ +# Cache Management Documentation + +[TOC] + +## Introduction + +Cache management is a critical aspect of optimizing the performance and scalability of websites and web applications. +Caching involves storing frequently accessed data in temporary storage, such as memory or disk, to reduce the time and +resources required to fetch the data from the original source. Proper cache management can greatly improve the response +time and overall user experience of a website. + +In this documentation, we will explore the cache management features in Magento 2, a popular PHP-based e-commerce +platform. We will discuss the different types of cache, how to configure and manage them, and provide code snippets and +examples to illustrate the concepts. + +## Types of Cache in Magento 2 + +Magento 2 offers several types of cache, each serving a specific purpose. Understanding these cache types is crucial for +efficient cache management. The main cache types in Magento 2 are: + +1. Configuration Cache: Stores the merged configuration data for the application. This cache speeds up the loading of + configuration settings by eliminating the need to parse and merge the configuration files on each request. + +2. Page Cache: Caches the entire HTML content of web pages, including blocks, layout, and other dynamic content. This + cache greatly improves the response time for frequently accessed pages. + +3. Block HTML Output Cache: Caches the output generated by individual blocks in Magento's layout system. This cache + minimizes the processing required to generate the HTML output of blocks, resulting in faster page rendering. + +4. Collection Data Cache: Caches the results of database queries performed to retrieve collections of database records. + This cache helps reduce the database load by storing the query results and serving them directly from the cache. + +5. EAV Entity Attribute Value Cache: Stores the attribute values of EAV entities, such as products and customers. This + cache avoids the need to retrieve attribute values from the database repeatedly, improving the performance of + attribute-related operations. + +## Cache Configuration and Management + +### Enable/Disable Cache + +Magento 2 provides a command-line tool, `bin/magento`, to enable or disable different cache types. To enable all cache +types, use the following command: + +``` +bin/magento cache:enable +``` + +To enable specific cache types, use the `--type` option followed by the cache type code. For example, to enable only the +page cache and block HTML output cache, use: + +``` +bin/magento cache:enable page_cache block_html +``` + +Similarly, to disable all cache types, use the following command: + +``` +bin/magento cache:disable +``` + +### Flush Cache + +Flushing the cache clears all stored cache data, forcing Magento to recompute and regenerate the cache on the next +request. To flush all cache types, run the following command: + +``` +bin/magento cache:flush +``` + +To flush specific cache types, use the `--type` option followed by the cache type code. For example, to flush only the +page cache and block HTML output cache, use: + +``` +bin/magento cache:flush page_cache block_html +``` + +### Cache Management from Admin Panel + +Magento 2 also provides a web-based cache management interface in the admin panel. To access it, navigate to **System +** -> **Cache Management**. From there, you can enable/disable individual cache types and flush the entire cache or +specific cache types. + +## Cache Invalidation + +Cache invalidation is the process of removing or updating cache data when the original data changes. In Magento 2, cache +invalidation is handled automatically for many cases, such as when a product is updated or a block's content changes. +However, there may be situations where you need to manually invalidate the cache. + +Magento 2 provides a cache tags mechanism to manage cache invalidation. Each cache entry is associated with one or more +cache tags, and when a tag is invalidated, all associated cache entries are cleared. You can use +the `Magento\Framework\App\Cache\Tag\Resolver` class to invalidate cache tags programmatically. + +Here is an example of cache tag invalidation in Magento 2: + +```php +cacheTagResolver = $cacheTagResolver; + } + + public function invalidateCacheTags(array $cacheTags) + { + foreach ($cacheTags as $cacheTag) { + $this->cacheTagResolver->invalidate($cacheTag); + } + } +} +``` + +In this example, the `invalidateCacheTags` method takes an array of cache tags and invalidates them using +the `invalidate` method of the `Resolver` class. + +## Types of Caching in Magento 2 + +Magento 2 offers several caching types, each designed to cache specific types of data. Let's explore the most commonly +used caching types in Magento 2. + +### Full Page Cache (FPC) + +Full Page Cache is a powerful caching mechanism in Magento 2 that stores fully rendered HTML pages. By caching the +entire page, including all blocks and elements, Magento can serve the cached page directly from memory without executing +expensive PHP code. + +Example: To enable FPC in Magento 2, navigate to **Stores > Configuration > Advanced > System > Full Page Cache** in the +Admin Panel. + +### Object Cache + +Object Cache caches individual objects or entities, such as products, categories, and customer data. When an object is +requested, Magento checks if it exists in the cache before fetching it from the database. + +Example: To cache an object in Magento 2, use the following code snippet: + +```php +$cacheKey = 'my_object_cache_key'; +$cacheValue = $this->cache->load($cacheKey); + +if (!$cacheValue) { + // Object not found in cache, fetch it from the database + $object = $this->objectRepository->getById($objectId); + + // Save the object in cache + $this->cache->save($object, $cacheKey, [], $cacheLifetime); +} else { + // Object found in cache, use it + $object = unserialize($cacheValue); +} +``` + +### Configuration Cache + +Configuration Cache stores the merged configuration data of your Magento 2 store. It includes the system configuration, +module configurations, and other XML-based configurations. By caching the configuration, Magento avoids parsing and +merging XML files on each request. + +Example: To enable Configuration Cache in Magento 2 via the command line, use the following command: + +``` +php bin/magento cache:enable config +``` + +### Layout Cache + +Layout Cache stores the layout XML for each page in your store. By caching the layout, Magento avoids parsing and +merging XML files on each request, leading to improved performance. + +Example: To enable Layout Cache in Magento 2 via the command line, use the following command: + +``` +php bin/magento cache:enable layout +``` + +### Block Cache + +Block Cache caches individual blocks within a page. By caching blocks, Magento can serve the cached block content +directly without executing the block's code. + +Example: To enable Block Cache for a specific block in Magento 2, add the following code to the block class: + +```php +protected function _construct() +{ + $this->addData([ + 'cache_lifetime' => 86400, // Cache lifetime in seconds + 'cache_key' => 'my_block_cache_key', + ]); +} +``` + +### Collection Cache + +Collection Cache caches the result of database queries made by collection objects. By caching collections, Magento +avoids executing the same database query multiple times, resulting in improved performance. + +Example: To cache a collection in Magento 2, use the following code snippet: + +```php +$cacheKey = 'my_collection_cache_key'; +$cacheValue = $this->cache->load($cacheKey); + +if (!$cacheValue) { + // Collection not found in cache, fetch it from the database + $collection = $this->collectionFactory->create(); + + // Save the collection in cache + $this->cache->save(serialize($collection->getData()), $cacheKey, [], $cacheLifetime); +} else { + // Collection found in cache, use it + $collection = unserialize($cacheValue); +} +``` + +### Metadata Cache + +Metadata Cache stores metadata related to various entities, such as attributes, tables, and configurations. By caching +metadata, Magento avoids querying the database for metadata information repeatedly. + +Example: To enable Metadata Cache in Magento 2 via the command line, use the following command: + +``` +php bin/magento cache:enable metadata +``` + +## Caching Configuration in Magento 2 + +Magento 2 provides multiple ways to configure caching. Let's explore the two most common methods. + +### Configuration via the Admin Panel + +You can configure caching options via the Magento 2 Admin Panel. Navigate to **Stores > Configuration > Advanced > +System > Cache Management**. Here, you can enable/disable specific cache types and configure cache settings. + +### Configuration via Command Line + +Alternatively, you can configure caching options via the command line using the `bin/magento cache` command. This method +is useful, especially when automating deployment processes or managing multiple environments. + +Example: To enable the Full Page Cache via the command line, use the following command: + +``` +php bin/magento cache:enable full_page +``` + +## Caching Strategies + +To ensure efficient utilization of caching, it's essential to consider proper caching strategies. Let's explore some +common caching strategies in Magento 2. + +### Automatic Cache Invalidation + +Magento 2 automatically invalidates caches when relevant data changes. For example, when a product is updated, the +associated caches (object, block, collection, etc.) are invalidated, ensuring that the updated data is fetched from the +original source. + +### Manual Cache Invalidation + +In some cases, you may need to manually invalidate specific caches, rather than relying on automatic invalidation. +Magento 2 provides cache management commands that allow you to flush specific cache types or all caches. + +Example: To flush the Object Cache via the command line, use the following command: + +``` +php bin/magento cache:flush customer +``` + +### Cache Tags + +Cache Tags are a powerful feature in Magento 2 that allow you to assign tags to cached items. When a cache with a +specific tag is invalidated, all associated cached items are also invalidated. This ensures that related data is +refreshed when any item in the group is modified. + +Example: To add a cache tag to an object cache in Magento 2, use the following code snippet: + +```php +$cacheKey = 'my_object_cache_key'; +$cacheValue = $this->cache->load($cacheKey, $cacheTag); + +if (!$cacheValue) { + // Object not found in cache, fetch it from the database + $object = $this->objectRepository->getById($objectId); + + // Save the object in cache with the cache tag + $this->cache->save($object, $cacheKey, [$cacheTag], $cacheLifetime); +} else { + // Object found in cache, use it + $object = unserialize($cacheValue); +} +``` + +## Utilizing Cache in Code + +Magento 2 provides convenient methods and classes to utilize caching in your custom code. Let's explore how to use +caching in code. + +### Cache Storage + +Magento 2 uses the `Magento\Framework\Cache\FrontendInterface` class to interact with the cache storage. You can inject +this class in your code to read from or write to the cache. + +Example: To inject the cache storage in a class constructor: + +```php +use Magento\Framework\Cache\FrontendInterface; + +class MyClass +{ + protected $cache; + + public function __construct( + FrontendInterface $cache + ) { + $this->cache = $cache; + } +} +``` + +### Reading from Cache + +To read data from the cache, use the `load($cacheKey)` method of the cache storage. If the data is not found in the +cache, you can fetch it from the original source and save it in the cache. + +### Writing to Cache + +To write data to the cache, use the `save($cacheValue, $cacheKey, $cacheTags, $cacheLifetime)` method of the cache +storage. Provide the cache value, cache key, associated cache tags (if any), and the cache lifetime in seconds. + +Example: To save data in the cache: + +```php +$cacheKey = 'my_cache_key'; +$cacheValue = 'my_cache_value'; +$cacheTags = ['tag1', 'tag2']; +$cacheLifetime = 86400; // 24 hours + +$this->cache->save($cacheValue, $cacheKey, $cacheTags, $cacheLifetime); +``` + +## Conclusion + +Understanding and effectively utilizing caching in Magento 2 can greatly improve the performance of your store. By +configuring the appropriate cache types, managing cache strategies, and leveraging caching in your custom code, you can +achieve faster response times and provide an optimal user experience for your customers. diff --git a/cache-xml.md b/cache-xml.md deleted file mode 100644 index e69de29..0000000 diff --git a/cache.md b/cache_xml.md similarity index 99% rename from cache.md rename to cache_xml.md index a2a79c8..9503074 100644 --- a/cache.md +++ b/cache_xml.md @@ -1,4 +1,6 @@ -# Cache.xml Reference Documentation +# `cache.xml` Reference Documentation + +[TOC] ## Introduction @@ -73,7 +75,6 @@ attribute to either `true` or `false` to enable or disable the cache type, respe ### Example: Disabling the `block_html` Cache Type ```xml - ``` diff --git a/caching-in-magento-2.md b/caching-in-magento-2.md deleted file mode 100644 index e69de29..0000000 diff --git a/case-studies-of-problem-solving-in-magento-2.md b/case-studies-of-problem-solving-in-magento-2.md index e69de29..f10dac5 100644 --- a/case-studies-of-problem-solving-in-magento-2.md +++ b/case-studies-of-problem-solving-in-magento-2.md @@ -0,0 +1,176 @@ +# Magento 2 Case Studies: Problem Solving Documentation + +[TOC] + +Welcome to the Magento 2 Case Studies documentation. In this document, we will explore real-life problem-solving +scenarios in Magento 2, a widely-used PHP-based e-commerce platform. Each case study will present a specific problem and +provide step-by-step instructions on how to approach and solve it. We will also include concrete examples and code +snippets to illustrate the concepts discussed. Please note that this document assumes you have some familiarity with +programming, specifically PHP and Magento 2, as it will use technical jargon and concepts that may be difficult for +non-technical readers to understand. Let's dive in! + +## Case Study 1: Optimizing SQL Queries + +### Problem: + +You have noticed that your Magento 2 store is running slow, particularly when loading category pages. After analyzing +the performance, you suspect that poorly optimized SQL queries are the root cause. + +### Solution: + +To optimize SQL queries in Magento 2, follow these steps: + +1. Enable SQL query logging in your Magento 2 installation. To do this, open your Magento 2 configuration + file (`app/etc/env.php`) and locate the `db` section. Set the `debug` parameter to `true` and save the file. + + ```php + 'db' => [ + 'table_prefix' => '', + 'connection' => [ + 'default' => [ + 'host' => 'localhost', + 'dbname' => 'magento', + 'username' => 'magento_user', + 'password' => 'magento_password', + 'active' => '1', + 'persistent' => null, + 'model' => 'mysql4', + 'engine' => 'innodb', + 'initStatements' => 'SET NAMES utf8;', + 'driver_options' => [ + PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true, + ], + 'debug' => 'true', // Set this to true + ], + ], + ], + ``` + +2. Perform the actions that trigger slow SQL queries in your Magento 2 store. This could include loading category pages + or performing searches. + +3. Check the generated SQL queries in the log files. Magento 2 logs SQL queries in the `var/debug/db.log` file. + +4. Identify the slow SQL queries by analyzing the logged queries. Look for queries that take longer to execute or have + inefficient joins or conditions. + +5. Analyze the slow queries and find opportunities for optimization. You can use EXPLAIN statements, database indexes, + or rewriting queries with better alternatives. + +6. Implement the optimizations identified in step 5. For example, you can add necessary indexes to the database tables + or refactor SQL queries to utilize more efficient joins or conditions. + +7. Test the performance after implementing the optimizations to ensure the desired improvements are achieved. + +Remember, optimizing SQL queries requires a deep understanding of the Magento 2 database structure and query execution. +It is recommended to consult with experienced Magento 2 developers or database administrators if you are unsure about +any optimizations. + +## Case Study 2: Customizing Checkout Process + +### Problem: + +You need to customize the checkout process in your Magento 2 store to meet specific business requirements. This includes +adding custom fields, modifying the order summary, and integrating with a third-party payment gateway. + +### Solution: + +To customize the checkout process in Magento 2, follow these steps: + +1. Identify the specific customizations required for your checkout process. This could include adding custom fields, + modifying existing fields, or integrating with a third-party payment gateway. + +2. Create a custom module in Magento 2 to encapsulate your checkout customizations. This module will contain all the + necessary code and configuration files. + +3. Define the custom fields required for the checkout process in your module's configuration + file (`etc/checkout_fields.xml`). This file specifies the field names, types, and validation rules. + + ```xml + + + Custom Field Label + + ``` + +4. Create a layout XML file (`view/frontend/layout/checkout_index_index.xml`) in your module to modify the checkout + layout. + + ```xml + + + + + + + + + + + + + + + + + Vendor_Module/js/view/custom-field + 0 + + shippingAddress.custom_attributes + ui/form/field + Vendor_Module/form/element/custom-field + + + true + + + + + + + + + + + + + + + + + ``` + +5. Create a JavaScript component (`view/frontend/web/js/view/custom-field.js`) to handle the custom field behavior. + + ```javascript + define([ + 'uiComponent' + ], function (Component) { + 'use strict'; + + return Component.extend({ + initialize: function () { + this._super(); + // Add custom field behavior here + } + }); + }); + ``` + +6. Implement the integration with the third-party payment gateway by extending the Magento 2 payment method model and + implementing the necessary API calls and callbacks. + +7. Test the checkout process thoroughly to ensure that the customizations are working as expected and integrating + correctly with the third-party payment gateway. + +Customizing the checkout process in Magento 2 requires a thorough understanding of the Magento 2 architecture, layout +XML files, JavaScript components, and payment gateway integrations. It is recommended to consult Magento 2 developer +documentation and seek guidance from experienced developers if you encounter any difficulties. + +## Conclusion + +In this documentation, we have explored two case studies of problem-solving in Magento 2. We discussed optimizing SQL +queries and customizing the checkout process, providing step-by-step instructions and concrete examples to illustrate +the concepts. Remember to approach problem-solving in Magento 2 with a deep understanding of the platform's architecture +and best practices. For further assistance, consult the Magento 2 documentation and seek guidance from experienced +Magento 2 developers. Happy problem-solving! diff --git a/ci-cd.md b/ci-cd.md deleted file mode 100644 index e69de29..0000000 diff --git a/cli-commands.md b/cli-commands.md index e69de29..67cf362 100644 --- a/cli-commands.md +++ b/cli-commands.md @@ -0,0 +1,105 @@ +# CLI Commands Documentation + +[TOC] + +## Introduction + +This document provides a comprehensive guide to the Command Line Interface (CLI) commands available in Magento 2. CLI +commands are powerful tools that allow developers and administrators to interact with Magento 2 from the command line. +By executing these commands, you can perform various tasks such as installing or updating modules, flushing caches, +compiling code, and more. + +## Prerequisites + +Before using the CLI commands, ensure that you have the following prerequisites: + +1. A working installation of Magento 2. +2. A command line interface, such as the Terminal or Command Prompt. +3. Familiarity with PHP and Magento 2 concepts. + +## Accessing CLI Commands + +To access the CLI commands, open a command line interface and navigate to the root directory of your Magento 2 +installation. Once you are in the correct directory, you can execute any available CLI command. + +## Syntax + +The basic syntax for executing a CLI command in Magento 2 is as follows: + +```bash +php bin/magento [command_name] [options] [arguments] +``` + +- `php` refers to the PHP executable. +- `bin/magento` is the entry point for all Magento CLI commands. +- `[command_name]` is the name of the specific command you want to execute. +- `[options]` are additional flags or parameters that modify the behavior of the command. +- `[arguments]` are specific values or variables required by the command. + +Note that square brackets indicate optional elements. + +## Common CLI Commands + +This section provides an overview of some commonly used CLI commands in Magento 2. + +### `setup:upgrade` + +The `setup:upgrade` command is used to upgrade the Magento 2 instance after installing or updating modules. It applies +database schema and data changes, ensuring that the system is up to date. + +Example usage: + +```bash +php bin/magento setup:upgrade +``` + +### `cache:flush` + +The `cache:flush` command flushes all caches in the Magento 2 system. This is useful after making changes that need to +be reflected immediately, such as modifying configuration files or updating module code. + +Example usage: + +```bash +php bin/magento cache:flush +``` + +### `module:enable` and `module:disable` + +The `module:enable` and `module:disable` commands allow you to enable or disable specific modules in Magento 2. Enabling +a module activates its functionality, while disabling it renders the module inactive. + +Example usage: + +```bash +php bin/magento module:enable My_Module +php bin/magento module:disable My_Module +``` + +### `setup:di:compile` + +The `setup:di:compile` command compiles the dependency injection configuration for Magento 2. This step is necessary +after modifying the codebase or adding new modules to ensure that all dependencies are correctly resolved. + +Example usage: + +```bash +php bin/magento setup:di:compile +``` + +### `cache:clean` + +The `cache:clean` command cleans the Magento 2 cache by removing all cached files. This is useful when troubleshooting +caching issues or when you want to start with a clean cache. + +Example usage: + +```bash +php bin/magento cache:clean +``` + +## Conclusion + +CLI commands in Magento 2 provide a powerful way to interact with the system from the command line. This documentation +has covered some commonly used commands, but Magento 2 offers a wide range of commands for various tasks. By +familiarizing yourself with these commands, you can enhance your development and administration workflow in Magento 2. diff --git a/continious-integration-continious-deployment.md b/continious-integration-continious-deployment.md new file mode 100644 index 0000000..8b8cb7d --- /dev/null +++ b/continious-integration-continious-deployment.md @@ -0,0 +1,129 @@ +# Continuous Integration and Continuous Deployment Documentation + +[TOC] + +## Introduction + +In today's fast-paced software development landscape, companies are constantly looking for ways to improve their +development processes. Continuous Integration (CI) and Continuous Deployment (CD) are two practices that have gained +popularity in recent years. They allow developers to automate the process of building, testing, and deploying their +software, resulting in faster and more reliable releases. + +This documentation will provide a comprehensive overview of Continuous Integration and Continuous Deployment concepts, +as well as practical examples of implementing these practices in a Magento 2 project. + +## Continuous Integration + +### What is Continuous Integration? + +Continuous Integration is the practice of frequently integrating code changes from multiple developers into a shared +repository. The goal is to detect and resolve integration issues as early as possible. This is achieved by automatically +building and testing the software whenever changes are made. + +The key principles of Continuous Integration include: + +- **Maintaining a Single Source Repository**: All developers work on a common codebase, ensuring that everyone is always + working on the latest version of the software. +- **Automated Build and Test Processes**: Code changes trigger automated build and test processes, allowing developers + to quickly identify and fix issues. +- **Fast Feedback Loop**: Developers receive immediate feedback on the quality of their code, enabling them to address + any issues promptly. + +### Benefits of Continuous Integration + +Continuous Integration offers several benefits, including: + +- **Early Detection of Issues**: By integrating and testing code frequently, issues are identified and resolved earlier + in the development process, reducing the cost and effort required for bug fixing. +- **Improved Collaboration**: Since all developers are working on a shared codebase, it fosters collaboration and + encourages knowledge sharing among team members. +- **Increased Confidence in Releases**: Continuous Integration ensures that software is always in a releasable state, + reducing the risk of introducing new bugs or breaking existing functionality. + +### Continuous Integration Workflow + +The typical Continuous Integration workflow involves the following steps: + +1. Developers make changes to the codebase and commit them to the shared repository. +2. A Continuous Integration server (such as Jenkins or Travis CI) monitors the repository for changes. +3. Upon detecting a change, the server automatically triggers the build process. +4. The build process compiles the code, runs automated tests, and generates artifacts (such as executable files or + deployment packages). +5. The server reports the build results and notifies the team of any issues. +6. Developers address any identified issues and repeat the process until the build is successful. + +### Implementing Continuous Integration with Magento 2 + +To implement Continuous Integration with Magento 2, you can utilize popular CI platforms like Jenkins or GitLab CI/CD. +Here's an example utilizing Jenkins: + +1. Set up a Jenkins server and configure it to monitor your Magento 2 repository for changes. +2. Create a Jenkins job that defines your build process. This job should include steps to: + + - Install dependencies and configure the build environment. + - Compile the code and generate necessary artifacts. + - Run automated tests to ensure code quality. + - Report build results and notify the team of any issues. + +3. Configure your Jenkins job to trigger on each commit to the repository. +4. Monitor the Jenkins console or receive notifications to promptly address any build issues. + +By implementing Continuous Integration for your Magento 2 project, you can ensure that code changes are reliably built, +tested, and integrated into your software. + +## Continuous Deployment + +### What is Continuous Deployment? + +Continuous Deployment is an extension of Continuous Integration that automates the process of releasing software to +production environments. It aims to minimize manual intervention and reduce the time between code changes and their +availability to end-users. + +With Continuous Deployment, every successful build from the Continuous Integration process is automatically deployed to +production, assuming it passes a set of predefined criteria (e.g., successful tests, code reviews, etc.). + +### Benefits of Continuous Deployment + +Continuous Deployment offers several benefits, including: + +- **Faster Time-to-Market**: By automating the deployment process, software updates can be released to production + rapidly, providing new features and bug fixes to end-users without delays. +- **Reduced Risk**: Automated deployment processes reduce the risk of human error, ensuring that deployments are + consistent and reliable across environments. +- **Improved Feedback Loop**: With Continuous Deployment, developers receive faster feedback from end-users, enabling + them to iterate and improve the software more rapidly. + +### Continuous Deployment Workflow + +The typical Continuous Deployment workflow involves the following steps: + +1. Developers commit code changes to the shared repository. +2. Continuous Integration process builds, tests, and verifies the code changes. +3. Upon successfully passing the Continuous Integration process, the build artifacts are automatically deployed to a + staging environment. +4. Automated tests are executed in the staging environment to ensure the changes work as expected. +5. If all tests pass, the deployment process proceeds to production, automatically deploying the changes to end-users. + +### Implementing Continuous Deployment with Magento 2 + +To implement Continuous Deployment with Magento 2, you can use deployment tools like Deployer, Capistrano, or GitLab +CI/CD. Here's an example utilizing GitLab CI/CD: + +1. Configure your GitLab CI/CD pipeline to trigger on each successful build from the Continuous Integration process. +2. Define a deployment stage in your GitLab CI/CD configuration that deploys the build artifacts to a staging + environment. +3. Execute automated tests in the staging environment to ensure the changes function correctly. +4. If the tests pass, define another deployment stage to automatically deploy the changes to production. + +By implementing Continuous Deployment for your Magento 2 project, you can automate the release process, reducing manual +effort and accelerating the delivery of new features and bug fixes to your end-users. + +## Conclusion + +Continuous Integration and Continuous Deployment are valuable practices that enable developers to build, test, and +release software more efficiently and reliably. By adopting these practices in your Magento 2 project, you can enhance +collaboration, increase confidence in releases, and deliver software updates to end-users faster. + +Remember to choose appropriate Continuous Integration and Continuous Deployment tools that fit the specific needs of +your project and team. With proper implementation and utilization, you can significantly improve your software +development process and achieve a more seamless and reliable release cycle. \ No newline at end of file diff --git a/core-features.md b/core-features.md index 8b3d724..725474c 100644 --- a/core-features.md +++ b/core-features.md @@ -1,21 +1,6 @@ # Core Features of Magento 2 -- [Core Features of Magento 2](#core-features-of-magento-2) - * [Catalog Management](#catalog-management) - * [Checkout, Payment, and Shipping](#checkout-payment-and-shipping) - * [SEO and Marketing](#seo-and-marketing) - * [Mobile Commerce](#mobile-commerce) - * [Analytics and Reporting](#analytics-and-reporting) - * [International Support](#international-support) - * [Customer Accounts](#customer-accounts) - * [Order Management](#order-management) - * [Security](#security) - * [Developer Tools](#developer-tools) - * [Multistore Functionality](#multistore-functionality) - * [Content Staging and Preview](#content-staging-and-preview) - * [ElasticSearch](#elasticsearch) - * [Page Builder](#page-builder) - * [Customer Loyalty Tools](#customer-loyalty-tools) +[TOC] Magento 2 is equipped with an extensive set of powerful features, designed to provide businesses with unparalleled flexibility, scalability, and control over their eCommerce platform. Here, we delve into a few key features. diff --git a/cron-groups-xml.md b/cron-groups-xml.md deleted file mode 100644 index e69de29..0000000 diff --git a/cron-jobs-xml.md b/cron-jobs-xml.md deleted file mode 100644 index e69de29..0000000 diff --git a/cron-jobs.md b/cron-jobs.md index 2335dc0..8acca75 100644 --- a/cron-jobs.md +++ b/cron-jobs.md @@ -1,33 +1,17 @@ # Cron Jobs in Magento 2 -- [Introduction](#introduction) -- [Setting up a Cron Job](#setting-up-a-cron-job) - - [Step 1: Declare the Cron Job in `crontab.xml`](#step-1) - - [Step 2: Define the Cron Job Method](#step-2) -- [Executing a Cron Job](#executing-a-cron-job) -- [Viewing and Managing Cron Tasks](#viewing-and-managing-cron-tasks) -- [Cron Groups](#cron-groups) - - [Defining a Cron Group](#defining-a-cron-group) - - [Running a Specific Cron Group](#running-a-specific-cron-group) - - [Benefits of Using Cron Groups](#benefits-of-using-cron-groups) -- [Best Practices for Cron Jobs](#best-practices-for-cron-jobs) - - -## Introduction +[TOC] +## Introduction Cron jobs are scheduled tasks that run automatically at specified intervals. Magento uses cron jobs to run tasks such as reindexing, generating reports, sending newsletters, and many more. Cron jobs are essential to keep your Magento 2 store functioning correctly. - ## Setting up a Cron Job - Setting up a cron job in Magento involves two main steps: declaring the cron job in the `crontab.xml` file, and defining the method that will be executed when the cron job runs. - ### Step 1: Declare the Cron Job in `crontab.xml` - First, we need to declare our cron job in a `crontab.xml` file. This file should be located in the `etc` directory of your module. If it doesn't exist, create one. @@ -52,9 +36,7 @@ In the above code: - `method`: This is the method in your class that will be called. - `schedule`: This determines how often your cron job will run, based on cron syntax. - ### Step 2: Define the Cron Job Method - Now, we need to create the cron class in the `Vendor\Module\Cron` directory and define the `execute()` method. This is the method that will be executed when the cron job runs. @@ -86,9 +68,7 @@ In this class: The `LoggerInterface` is used to log messages. The `execute()` method logs a message when the cron job runs successfully. - ## Executing a Cron Job - To execute all Magento cron jobs, you run the following command in the terminal: ```bash @@ -97,9 +77,7 @@ php bin/magento cron:run This command will execute all cron jobs that are scheduled to run at the time the command is executed. - ## Viewing and Managing Cron Tasks - To view a list of all scheduled cron jobs and their status, you can use the following command: ```bash @@ -117,15 +95,11 @@ php bin/magento cron:remove Replace `` with the code of the job you wish to remove. - ## Cron Groups - Magento 2 uses cron groups to manage related tasks together. A cron group is a set of cron jobs that are managed as a unit. All cron jobs in a group will run in the same process to ensure the resources are effectively used. - ### Defining a Cron Group - Cron groups are defined in the `crontab.xml` file in the same way as individual cron jobs. The `group id` attribute is used to define the group. Jobs within the same group are enclosed within the same `group` tags. @@ -148,9 +122,7 @@ Here is an example of how to define a cron group: In this example, both `my_cronjob1` and `my_cronjob2` are part of `the my_cron_group group`. - ### Running a Specific Cron Group - To run all jobs in a specific cron group, use the following command: ```bash @@ -159,9 +131,7 @@ php bin/magento cron:run --group="my_cron_group" This command will run all cron jobs in `the my_cron_group group`. - ### Benefits of Using Cron Groups - Using cron groups provides a few benefits: You can manage related cron jobs together, making your cron configuration easier to understand and maintain. @@ -170,12 +140,10 @@ If an error occurs in one job, it won't affect the other jobs in the group. Remember, the effective management of cron jobs, including the use of cron groups, is vital for maintaining the performance and functionality of your Magento 2 store. - ## Best Practices for Cron Jobs - - Always log the start, end, and any exceptions in your cron jobs. This will help in debugging issues later. - Always return $this at the end of your cron job method to ensure that the method chain isn't broken. - Don't overload your server with too many simultaneous cron jobs. Schedule your jobs efficiently to avoid high server load. - Keep the execution time of your cron jobs as short as possible. Long-running jobs can slow down the overall - performance of your Magento store. + performance of your Magento store. \ No newline at end of file diff --git a/cron_groups_xml.md b/cron_groups_xml.md new file mode 100644 index 0000000..ffbd478 --- /dev/null +++ b/cron_groups_xml.md @@ -0,0 +1,155 @@ +# `cron_groups.xml` Reference Documentation + +[TOC] + +## Overview + +The `cron_groups.xml` file is a configuration file used in Magento 2 to define cron groups and their associated cron +jobs. Cron jobs are scheduled tasks that are executed automatically at specified intervals. Cron groups allow you to +categorize and manage cron jobs more effectively. + +This reference documentation will provide you with a detailed explanation of the `cron_groups.xml` file and its +structure. It will also cover the various elements and attributes used in this file, along with their purpose and usage. + +## File Location + +The `cron_groups.xml` file is located in the `/etc` directory of your Magento 2 module. It follows the `XML` +file format and can be edited using any text editor or integrated development environment (IDE) of your choice. + +## File Structure + +The `cron_groups.xml` file follows a specific structure that consists of several XML elements and attributes. Here is an +example of the basic structure: + +```xml + + + + 1 + 4 + 2 + 10 + 60 + 600 + 0 + + + +``` + +The root element of the file is ``, which contains several child elements representing cron groups. Each cron +group is defined within a `` element, with a unique `id` attribute identifying it. The various configurations for +each cron group are specified as child elements within the `` element. + +## Elements and Attributes + +### `` + +The `` element represents a cron group and contains various child elements for configuring the group. It has the +following attribute: + +- `id` (required): Specifies a unique identifier for the cron group. This identifier is referenced in other + configuration files to assign cron jobs to this group. + +Example: + +```xml + + + + +``` + +### `` + +The `` element determines how often the cron schedule is regenerated. It sets the frequency in +minutes for generating the cron schedule. + +Example: + +```xml + +1 +``` + +### `` + +The `` element specifies the number of minutes ahead of the current time for which the cron schedule +is generated. It helps in ensuring that scheduled tasks are executed on time by allowing a buffer for processing. + +Example: + +```xml + +4 +``` + +### `` + +The `` element defines the maximum number of minutes for which a cron job can be scheduled. After +this time, the schedule entry for the cron job will be removed from the schedule tables. + +Example: + +```xml + +2 +``` + +### `` + +The `` element determines how often the cron history is cleaned up. It sets the frequency in +minutes for cleaning up the history of executed cron jobs. + +Example: + +```xml + +10 +``` + +### `` + +The `` element specifies the number of minutes after which successful cron job entries are +removed from the history tables. + +Example: + +```xml + +60 +``` + +### `` + +The `` element defines the number of minutes after which failed cron job entries are removed +from the history tables. + +Example: + +```xml + +600 +``` + +### `` + +The `` element determines whether cron jobs assigned to the cron group should be executed in a +separate process. It accepts a boolean value: `0` for false and `1` for true. + +Example: + +```xml + +0 +``` + +## Conclusion + +The `cron_groups.xml` file is a crucial configuration file used in Magento 2 for defining cron groups and their +associated cron jobs. By understanding its structure and the various elements and attributes it provides, you can +effectively manage and schedule cron jobs within your Magento 2 module. + +Remember to make any necessary modifications to this file with caution, as incorrect configurations may lead to +unexpected behaviors or issues with your cron jobs. diff --git a/cron_jobs.md b/cron_jobs_xml.md similarity index 98% rename from cron_jobs.md rename to cron_jobs_xml.md index 243d1a2..9a830a5 100644 --- a/cron_jobs.md +++ b/cron_jobs_xml.md @@ -1,4 +1,6 @@ -# Cron Jobs XML Reference Documentation +# `cron_jobs.xml` Reference Documentation + +[TOC] ## Introduction diff --git a/css-preprocessing.md b/css-preprocessing.md index e69de29..1bc73b9 100644 --- a/css-preprocessing.md +++ b/css-preprocessing.md @@ -0,0 +1,219 @@ +# CSS Preprocessing Documentation + +[TOC] + +## Introduction + +CSS preprocessing is a technique used to enhance the functionality and flexibility of CSS (Cascading Style Sheets). It +involves using a preprocessor to write CSS in a more dynamic and efficient manner. This documentation will provide an +overview of CSS preprocessing, explain its benefits, and discuss some popular CSS preprocessors such as Sass and Less. +Additionally, we will explore how CSS preprocessing can be utilized in PHP and Magento 2 environments. + +## What is CSS Preprocessing? + +CSS preprocessing is the process of writing CSS using a preprocessor, which is a tool that extends the capabilities of +CSS by adding features like variables, mixins, nesting, and more. These features allow developers to write CSS in a more +modular and reusable way, resulting in cleaner and more maintainable code. + +Preprocessors work by taking input files written in a preprocessor language and transforming them into valid CSS files +that can be interpreted by browsers. This transformation is typically done using a command-line tool or a build system. + +## Benefits of CSS Preprocessing + +CSS preprocessing offers several key benefits for web developers: + +### 1. Variables + +CSS preprocessors allow the use of variables, which can be defined once and reused throughout the codebase. This makes +it easier to maintain consistency in styling, as changes to a variable value will be automatically reflected across all +instances. + +Example: + +```scss +$primary-color: #007bff; +.button { + background-color: $primary-color; +} +``` + +### 2. Mixins + +Mixins are reusable blocks of CSS code that can be included in multiple selectors. They allow developers to define +complex styles once and apply them wherever needed. This reduces code duplication and improves code organization. + +Example: + +```scss +@mixin button-styles { + padding: 10px; + background-color: $primary-color; + color: white; + border-radius: 5px; +} + +.button { + @include button-styles; +} + +.submit-button { + @include button-styles; + background-color: green; +} +``` + +### 3. Nesting + +CSS preprocessors support nesting, allowing developers to nest selectors inside other selectors. This makes the code +structure more intuitive and easier to read. + +Example: + +```scss +.container { + background-color: #f1f1f1; + + .button { + padding: 10px; + background-color: $primary-color; + color: white; + } +} +``` + +### 4. Extending + +Preprocessors support extending, which enables the inheritance of styles from one selector to another. This promotes +code reuse and reduces redundancy. + +Example: + +```scss +.button { + padding: 10px; + background-color: $primary-color; + color: white; +} + +.submit-button { + @extend .button; + background-color: green; +} +``` + +### 5. Modularity + +CSS preprocessors allow developers to split their code into multiple files, making it easier to manage and organize +styles. These files can then be imported into a single master file, which will be compiled into a single CSS file by the +preprocessor. + +Example: + +```scss +// base.scss +$primary-color: #007bff; + +.button { + padding: 10px; + background-color: $primary-color; + color: white; +} + +// main.scss +@import 'base'; + +.container { + ... +} +``` + +## Popular CSS Preprocessors + +There are several popular CSS preprocessors available, but two of the most widely used are Sass (Syntactically Awesome +Style Sheets) and Less. Both preprocessors offer similar features and are supported by a large community. + +### Sass + +Sass is a powerful and mature CSS preprocessor that provides a wide range of features. It has a large and active +community, making it easy to find resources and support. Sass supports two syntaxes: SCSS (Sassy CSS), which is a +superset of CSS, and the indented syntax. + +To compile Sass files into CSS, you can use the command line or build tools like Grunt, Gulp, or Webpack. + +Example of SCSS syntax: + +```scss +$primary-color: #007bff; + +.button { + padding: 10px; + background-color: $primary-color; + color: white; +} +``` + +Example of indented syntax: + +```sass +$primary-color: #007bff + +.button + padding: 10px + background-color: $primary-color + color: white +``` + +### Less + +Less is another popular CSS preprocessor that provides similar features to Sass. It has a more concise syntax compared +to Sass, resembling traditional CSS. Less also has a large community and can be compiled using command-line tools or +build systems. + +Example: + +```less +@primary-color: #007bff; + +.button { + padding: 10px; + background-color: @primary-color; + color: white; +} +``` + +## Using CSS Preprocessing in PHP and Magento 2 + +CSS preprocessing can be integrated into PHP and Magento 2 projects to enhance the styling capabilities. To utilize CSS +preprocessors in these environments, additional setup steps are required. + +1. **PHP**: To use CSS preprocessing in PHP projects, you need to set up a build system or task runner like Grunt, Gulp, + or Webpack. These tools can be configured to watch and compile your preprocessor files into CSS whenever changes are + made. The compiled CSS files can then be included in your PHP files as usual. + +2. **Magento 2**: Magento 2 utilizes the LESS preprocessor by default for its frontend styles. To customize and extend + styles in Magento 2, you can create a custom theme and override the default LESS files. This allows you to leverage + the power of LESS and its preprocessing features within the Magento 2 framework. + +Example of overriding a LESS file in a Magento 2 custom theme: + +``` +app/design/frontend/MyVendor/my-theme/web/css/source/_extend.less +``` + +```less +@primary-color: #007bff; + +.button { + padding: 10px; + background-color: @primary-color; + color: white; +} +``` + +## Conclusion + +CSS preprocessing is a powerful technique that enhances the capabilities of CSS by introducing features like variables, +mixins, nesting, and more. By using CSS preprocessors like Sass or Less, developers can write cleaner and more +maintainable code. In PHP and Magento 2 environments, CSS preprocessing can be integrated with build systems or custom +themes to unlock the full potential of CSS preprocessing. Experiment with CSS preprocessors and experience the benefits +of improved organization, modularity, and code reusability in your projects. diff --git a/data-interfaces-and-models.md b/data-interfaces-and-models.md index e69de29..d3bbff6 100644 --- a/data-interfaces-and-models.md +++ b/data-interfaces-and-models.md @@ -0,0 +1,130 @@ +# Data Interfaces and Models Documentation + +[TOC] + +## Introduction + +Data interfaces and models are essential components in Magento 2 development. They provide a structured way to represent +and manipulate data, ensuring consistency and maintainability in your codebase. This documentation will explore the +concepts of data interfaces and models in Magento 2, their purpose, and how to use them effectively. + +## Data Interfaces + +Data interfaces define the structure and behavior of data objects in Magento 2. They act as contracts that enforce a set +of methods that must be implemented by any class that wants to use or manipulate the data. + +Data interfaces are typically defined in the `Api/Data` directory of a module and follow a naming convention +of `EntityInterface`. For example, if you have a module called `Vendor_Module`, the data interface for a custom entity +could be defined in `Vendor/Module/Api/Data/CustomEntityInterface.php`. + +Let's take a look at an example data interface for a `CustomEntity`: + +```php +_init(\Vendor\Module\Model\ResourceModel\CustomEntity::class); + } + + /** + * Get the entity ID. + * + * @return int|null + */ + public function getId() + { + return $this->getData(self::ID); + } + + /** + * Set the entity ID. + * + * @param int $id + * @return $this + */ + public function setId($id) + { + return $this->setData(self::ID, $id); + } + + // Other methods... +} +``` + +In this example, the `CustomEntity` model extends the `AbstractModel` class provided by Magento 2. This abstract class +provides common functionality for models, such as data storage and retrieval. + +The model implements the `CustomEntityInterface`, which enforces the implementation of the methods defined in the +interface. The implementation of the methods simply delegates the calls to the `getData()` and `setData()` methods +provided by the `AbstractModel` class. + +Models should also define a constructor that initializes the resource model. The resource model is responsible for +interacting with the database or other data storage mechanisms. In this example, the resource model for `CustomEntity` +is defined in `Vendor/Module/Model/ResourceModel/CustomEntity.php`. + +By utilizing models, you can encapsulate the logic for retrieving and manipulating data in a structured and consistent +manner. + +## Conclusion + +Data interfaces and models play a crucial role in Magento 2 development, providing a structured way to represent and +manipulate data. By defining data interfaces, you can enforce a consistent contract for interacting with data objects. +Models, on the other hand, are responsible for implementing these interfaces, encapsulating the logic for data retrieval +and manipulation. + +By following the conventions and best practices outlined in this documentation, you can ensure the maintainability and +consistency of your Magento 2 codebase. diff --git a/database-access-and-orm.md b/database-access-and-orm.md index e69de29..af8f425 100644 --- a/database-access-and-orm.md +++ b/database-access-and-orm.md @@ -0,0 +1,188 @@ +# Database Access and ORM Documentation + +[TOC] + +## Introduction + +Database access and Object-Relational Mapping (ORM) are fundamental concepts in software development. In this +documentation, we will explore the various aspects of database access and ORM, specifically in the context of PHP and +Magento 2. We will discuss the importance of these concepts, their benefits, and provide concrete examples and code +snippets to demonstrate their usage. + +## Database Access + +### Connecting to a Database + +To interact with a database in PHP, you need to establish a connection. In Magento 2, this can be achieved using +the `Magento\Framework\App\ResourceConnection` class. Here's an example: + +```php +get(ResourceConnection::class)->getConnection(); +``` + +### Executing Queries + +Once you have a connection, you can execute SQL queries. The `Magento\Framework\DB\Adapter\AdapterInterface` interface +provides methods like `query`, `fetchRow`, `fetchAll`, etc., to execute queries and retrieve results. Here's an example: + +```php +select() + ->from('catalog_product_entity') + ->where('price > ?', 100); + +$result = $connection->fetchAll($select); +``` + +### Retrieving Data + +Fetching data from a database table involves executing a query and processing the results. You can use the `fetchRow` +method to retrieve a single row, or `fetchAll` to get multiple rows as an array. Here's an example: + +```php +select() + ->from('catalog_product_entity') + ->where('entity_id = ?', $productId); + +$product = $connection->fetchRow($select); + +echo $product['name']; +``` + +### Inserting Data + +To insert data into a database table, you can use the `insert` method provided by the `AdapterInterface`. Here's an +example: + +```php + 'New Product', + 'price' => 99.99, +]; + +$connection->insert('catalog_product_entity', $data); +``` + +### Updating Data + +Updating existing data in a database table is done using the `update` method. You specify the table name, the data to +update, and any conditions. Here's an example: + +```php + 109.99, +]; + +$where = ['entity_id = ?' => 42]; + +$connection->update('catalog_product_entity', $data, $where); +``` + +### Deleting Data + +To delete data from a database table, you can use the `delete` method. It requires the table name and any conditions to +specify which rows to delete. Here's an example: + +```php + 42]; + +$connection->delete('catalog_product_entity', $where); +``` + +## ORM (Object-Relational Mapping) + +### Mapping Database Tables to PHP Classes + +ORM allows you to map database tables to PHP classes, making it easier to work with data in an object-oriented manner. +In Magento 2, this is achieved using the Entity-Attribute-Value (EAV) system. Each database table corresponds to an +entity, and each column represents an attribute. Here's an example: + +```php +_init('Vendor\Module\Model\ResourceModel\Product'); + } +} +``` + +### CRUD Operations with ORM + +ORM simplifies CRUD (Create, Read, Update, Delete) operations by providing methods to perform these operations on +entities. For example, to create a new entity, you can use the `create` method. Here's an example: + +```php +get(ProductFactory::class)->create(); +$product->setName('New Product'); +$product->setPrice(99.99); +$product->save(); +``` + +### Fetching Related Data + +ORM allows you to easily fetch related data using relationships defined in the entity classes. For example, if +a `Product` entity has a many-to-one relationship with a `Category` entity, you can fetch the category of a product +using the `getCategory` method. Here's an example: + +```php +get(ProductFactory::class)->create()->load($productId); +$category = $product->getCategory(); +``` + +### Updating and Saving Entities + +Updating an entity is as simple as loading it and modifying its attributes. Once you've made the changes, you can save +the entity back to the database using the `save` method. Here's an example: + +```php +get(ProductFactory::class)->create()->load($productId); +$product->setName('Updated Product'); +$product->save(); +``` + +### Deleting Entities + +To delete an entity, you can use the `delete` method. Here's an example: + +```php +get(ProductFactory::class)->create()->load($productId); +$product->delete(); +``` + +## Conclusion + +In this documentation, we covered the concepts of database access and ORM in PHP and Magento 2. We discussed connecting +to a database, executing queries, retrieving and manipulating data, and using ORM for simplified CRUD operations. By +leveraging these concepts effectively, you can build robust and efficient applications that interact seamlessly with +databases. diff --git a/db-schema-xml.md b/db-schema-xml.md deleted file mode 100644 index e69de29..0000000 diff --git a/db_schema_xml.md b/db_schema_xml.md new file mode 100644 index 0000000..1680613 --- /dev/null +++ b/db_schema_xml.md @@ -0,0 +1,126 @@ +# `db_schema.xml` Reference Documentation + +[TOC] + +## Introduction + +The `db_schema.xml` file is an essential part of the Magento 2 module development process. It provides a way to define +the database schema for your module, including tables, columns, indexes, and other related entities. This reference +documentation aims to explain the various elements and attributes used in the `db_schema.xml` file and provide concrete +examples and code snippets for better understanding. + +## File Structure + +The `db_schema.xml` file should be located in the `etc` directory of your module. It follows a specific XML structure, +as follows: + +```xml + + + + +``` + +In the above code snippet, you can see the XML declaration at the beginning and the root `schema` element, which serves +as the container for defining your module's database schema. + +## Tables + +To define a table in your module's schema, you should use the `table` element within the `schema` element. The `table` +element can have the following attributes: + +- `name`: The name of the table. +- `resource`: The resource name used to retrieve a database connection. +- `engine`: The storage engine used for the table (optional, defaults to `innodb`). + +Here's an example of defining a table in the `db_schema.xml` file: + +```xml + + + + +
+
+``` + +## Columns + +Within a table, you can define columns using the `column` element. The `column` element can have the following +attributes: + +- `name`: The name of the column. +- `dataType`: The data type of the column. +- `length`: The length of the column (optional, depends on the data type). +- `nullable`: Whether the column allows NULL values (`true` or `false`, optional, defaults to `false`). +- `comment`: A descriptive comment for the column (optional). + +Here's an example of defining columns within a table: + +```xml + + + + + +
+``` + +## Indexes + +You can define indexes for a table using the `index` element within the `table` element. The `index` element can have +the following attributes: + +- `name`: The name of the index. +- `indexType`: The type of the index (`btree`, `fulltext`, or `hash`, optional, defaults to `btree`). +- `referenceId`: The name of the column being referenced by the index. +- `referenceTable`: The name of the table being referenced by the index. + +Here's an example of defining an index within a table: + +```xml + + + + + + + + +
+``` + +## Foreign Keys + +To define a foreign key constraint between two tables, you can use the `constraint` element within the `table` element. +The `constraint` element can have the following attributes: + +- `name`: The name of the foreign key constraint. +- `referenceId`: The name of the column being referenced by the foreign key. +- `referenceTable`: The name of the table being referenced by the foreign key. +- `onDelete`: The action to perform when the referenced row is deleted (`cascade`, `set null`, `set default`, + or `restrict`, optional, defaults to `restrict`). +- `onUpdate`: The action to perform when the referenced row is updated (`cascade`, `set null`, `set default`, + or `restrict`, optional, defaults to `restrict`). + +Here's an example of defining a foreign key constraint within a table: + +```xml + + + + + + +
+``` + +## Conclusion + +The `db_schema.xml` file provides a way to define the database schema for your Magento 2 module. By understanding its +elements and attributes, you can effectively define tables, columns, indexes, and foreign keys. This reference +documentation aimed to provide a comprehensive overview of the `db_schema.xml` file and its usage in Magento 2 module +development. diff --git a/developing-extensions-in-magento-2.md b/developing-extensions-in-magento-2.md index e69de29..6b94daa 100644 --- a/developing-extensions-in-magento-2.md +++ b/developing-extensions-in-magento-2.md @@ -0,0 +1,240 @@ +# Magento 2 Extension Development Documentation + +[TOC] + +Welcome to the documentation for developing extensions in Magento 2. This guide will provide you with all the necessary +information to get started with building extensions for the Magento 2 platform. Whether you are a seasoned Magento +developer or just starting out, this documentation will help you understand the process and best practices for creating +powerful extensions. + +## 1. Introduction + +Magento 2 provides a robust and flexible architecture for building extensions that enhance the functionality of the +platform. Extensions can modify existing features or introduce new ones, allowing merchants to customize their Magento +stores to meet their specific business requirements. + +This documentation will cover various aspects of extension development, including extension structure, customizing +Magento 2, working with events and observers, creating command line interface commands, packaging and installing +extensions, and best practices to follow when developing extensions. + +## 2. Prerequisites + +Before diving into extension development, it is important to have a good understanding of PHP and Magento 2. Familiarize +yourself with the core concepts and architecture of Magento 2, as well as the programming language features of PHP. + +To get started with extension development, you will need the following: + +- A development environment with Magento 2 installed. +- A code editor or IDE of your choice. +- Knowledge of PHP, XML, and JavaScript (depending on the requirements of your extension). + +## 3. Extension Structure + +A Magento 2 extension follows a specific directory structure that Magento recognizes. Below is an example structure for +a basic extension called "MyExtension": + +``` +MyExtension/ +├── etc/ +│ ├── module.xml +│ └── ... +├── Block/ +│ ├── MyBlock.php +│ └── ... +├── Controller/ +│ ├── Index/ +│ │ └── Index.php +│ └── ... +├── Model/ +│ ├── MyModel.php +│ └── ... +├── view/ +│ └── frontend/ +│ ├── layout/ +│ │ ├── myextension_index_index.xml +│ │ └── ... +│ ├── templates/ +│ │ ├── myextension.phtml +│ │ └── ... +│ └── ... +└── ... +``` + +The `etc` directory contains the module configuration file `module.xml`, where you define the extension's name, version, +and other important details. + +The `Block`, `Controller`, and `Model` directories are where your PHP classes reside. These classes are responsible for +the business logic of your extension. + +The `view` directory is where you define the frontend and backend layouts, templates, and other view-related files for +your extension. + +## 4. Creating an Extension + +To create a new extension, follow these steps: + +1. Create a new directory inside the `app/code` directory of your Magento installation. For + example, `app/code/MyVendor/MyExtension`. +2. Inside the extension directory, create the necessary subdirectories (`etc`, `Block`, `Controller`, `Model`, `view`, + etc.) as per your extension's requirements. +3. Create the `module.xml` file inside the `etc` directory. This file should contain basic information about your + extension, such as its name, version, and dependencies. +4. Start creating your PHP classes, templates, layout files, etc., as required by your extension. + +## 5. Customizing Magento 2 + +Magento 2 allows you to customize various aspects of the platform by overriding core files. Here are some examples of +customizations you can make: + +### Overriding Templates + +To override a template file, create a new template file in your extension's directory and specify the original template +file to override in your layout XML file. For example: + +```xml + + +``` + +### Overriding Layouts + +To override a layout file, create a new layout XML file in your extension's directory and specify the original layout +file to override. For example: + +```xml + + + + MyVendor_MyExtension::product/price.phtml + + +``` + +### Overriding Controllers + +To override a controller, create a new controller class in your extension's directory and extend the original controller +class. For example: + +```php + + +To override a model, create a new model class in your extension's directory and extend the original model class. For +example: + +```php + + +Magento 2 provides an event-driven architecture that allows you to listen for specific events and execute custom code. +This is achieved using events and observers. + +### Creating an Observer + +To create an observer, you need to define it in the `events.xml` file of your extension and create the corresponding +observer class. For example: + +```xml + + + + +``` + +```php + + +To dispatch an event, you can use the event manager instance in your code. For example: + +```php +eventManager = $eventManager; + } + + public function someMethod() + { + // Dispatching the custom event + $this->eventManager->dispatch('myextension_custom_event', ['data' => $someData]); + } +} +``` + +### Listening to an Event + +To listen to an event, create an observer class as shown in the previous example and define it in the `events.xml` file +of your extension. + +## 7. Creating a Command Line Interface (CLI) Command + +Magento 2 allows you to create custom CLI commands that can be executed from the command line. To create a CLI command, +follow these steps: + +1. Create a PHP class that extends the `Command` class from the `Symfony\Component\Console` namespace. +2. Implement the necessary methods, including `configure` and `execute`, which define the command's configuration and + behavior. +3. Register your command in the `di.xml` file of your extension. + +## 8. Packaging and Installing Extensions + +To package and install your extension, you need to create a module package. This can be done using the Composer +packaging mechanism. Refer to the official Magento 2 documentation for detailed instructions on how to package and +install extensions. + +## 9. Testing Extensions + +Testing is an integral part of extension development. Magento 2 provides a testing framework that allows you to write +unit tests, integration tests, and functional tests for your extensions. Follow the official Magento 2 testing +documentation for guidelines on how to write tests for your extensions. + +## 10. Best Practices + +Here are some best practices to keep in mind when developing Magento 2 extensions: + +- Follow Magento's coding standards and best practices. +- Use dependency injection to decouple your classes and improve testability. +- Leverage the Magento 2 cache system to improve performance. +- Write clear and meaningful documentation for your extension. +- Regularly update your extension to ensure compatibility with new Magento versions. + +Congratulations! You now have a comprehensive understanding of Magento 2 extension development. Start exploring the vast +possibilities of extending Magento 2 and creating powerful customizations for your clients or projects. Happy coding! diff --git a/di-xml.md b/di-xml.md deleted file mode 100644 index e69de29..0000000 diff --git a/di_xml.md b/di_xml.md new file mode 100644 index 0000000..0a64e63 --- /dev/null +++ b/di_xml.md @@ -0,0 +1,105 @@ +# `di.xml` Reference Documentation + +[TOC] + +## Introduction + +The `di.xml` file is a crucial configuration file in Magento 2 that controls the dependency injection (DI) framework. It +is used to define and manage dependencies between objects in a Magento installation. This file allows developers to +configure how objects are instantiated and how they are injected into other objects. + +In this reference documentation, we will explore the structure and syntax of the `di.xml` file, and explain how to use +it to manage dependencies effectively in your Magento 2 project. + +## File Location + +By default, the `di.xml` file is located in the `etc` directory of a module. The complete path to the file +is `app/code/{Vendor}/{Module}/etc/di.xml`. For example, if you have a module called `MyModule` developed by +vendor `MyVendor`, the path to the `di.xml` file would be `app/code/MyVendor/MyModule/etc/di.xml`. + +## Syntax + +The `di.xml` file uses XML syntax to define and configure dependencies. It consists of a root `` element, which +contains multiple `` elements. Each `` element represents a class or interface for which dependencies are +defined. Within a `` element, you can have multiple `` and `` elements. + +Here's an example of the basic structure of a `di.xml` file: + +```xml + + + + + + +``` + +Let's examine each component of this structure in detail. + +### `` Element + +The `` element is the main building block of the `di.xml` file. It represents a class or interface for which +dependencies are defined. The `name` attribute of the `` element specifies the fully qualified class or interface +name. + +For example, if we want to configure dependencies for the `Magento\Catalog\Api\ProductRepositoryInterface` interface, +the `` element would look like this: + +```xml + + + + +``` + +### `` Element + +The `` element is used to define constructor arguments for a class. Within the `` element, you can +have multiple `` elements. Each `` element represents a constructor argument. + +Here's an example of how to define constructor arguments for the `Magento\Catalog\Api\ProductRepositoryInterface` +interface: + +```xml + + + + Magento\Catalog\Model\ProductFactory + Magento\Catalog\Model\ResourceModel\Product + + +``` + +In this example, we define two constructor arguments, namely `productFactory` and `resourceModel`. The `xsi:type` +attribute specifies the type of the argument, which can be either `object` or `string`. The `name` attribute specifies +the name of the argument, which can be any valid string. + +### `` Element + +The `` element is used to define a plugin for a class. Plugins are used to modify the behavior of existing class +methods by intercepting their execution. + +To define a plugin, you need to specify the `` of the class you want to plugin, the `` type (a class that +implements the plugin), and the name of the method you want to intercept. + +Here's an example of how to define a plugin for the `Magento\Catalog\Api\ProductRepositoryInterface` interface: + +```xml + + + + +``` + +In this example, we define a plugin with the name `my_plugin`, implemented by the +class `MyVendor\MyModule\Plugin\ProductRepositoryPlugin`. We also specify the `sortOrder` attribute to control the order +in which plugins are executed, and the `disabled` attribute to enable or disable the plugin. + +## Conclusion + +The `di.xml` file is a powerful tool for managing dependencies in Magento 2. By understanding its structure and syntax, +you can effectively configure and control how objects are instantiated and injected in your Magento project. + +This reference documentation has covered the basic components and syntax of the `di.xml` file. We hope that this +information will help you confidently navigate and utilize the power of the Magento 2 DI framework. diff --git a/diagrams-to-visually-represent-the-architecture.md b/diagrams-to-visually-represent-the-architecture.md index e69de29..8cd9eea 100644 --- a/diagrams-to-visually-represent-the-architecture.md +++ b/diagrams-to-visually-represent-the-architecture.md @@ -0,0 +1,146 @@ +# Architecture Diagrams Documentation + +[TOC] + +This documentation provides an overview of architecture diagrams, which are visual representations of a system's +structure and components. Architecture diagrams are often used to communicate the design and organization of a system to +stakeholders, developers, and other team members. In the context of this documentation, we will focus on using diagrams +to represent the architecture of PHP and Magento 2 applications. + +## Introduction to Architecture Diagrams + +Architecture diagrams provide a high-level view of the structure and components of a system. They help developers and +stakeholders visualize how different parts of the system interact and communicate with each other. By representing the +architecture visually, diagrams make it easier to understand complex systems and identify potential design flaws or +bottlenecks. + +In the context of PHP and Magento 2 applications, architecture diagrams can help illustrate the relationships between +modules, classes, and components. They can also show the flow of data between different parts of the system, such as the +frontend, backend, and databases. + +## Types of Architecture Diagrams + +There are several types of architecture diagrams that are commonly used in PHP and Magento 2 applications. Some of the +most common types include: + +### 1. High-Level System Diagrams + +High-level system diagrams provide an overview of the entire system and its major components. These diagrams are useful +for understanding the overall structure and organization of a PHP or Magento 2 application. For example, a high-level +system diagram for a Magento 2 e-commerce application might include components such as the frontend, backend, database, +and external services. + +### 2. Layered Architecture Diagrams + +Layered architecture diagrams show the different layers or tiers of an application and how they interact with each +other. In PHP and Magento 2 applications, common layers include the presentation layer (frontend), application layer, +domain layer, and data layer. These diagrams help visualize the separation of concerns and the flow of data between +layers. + +### 3. Component Diagrams + +Component diagrams focus on the individual components or modules within an application. These diagrams show how +different components interact with each other and communicate. In PHP and Magento 2 applications, components can include +modules, classes, libraries, and external dependencies. + +### 4. Sequence Diagrams + +Sequence diagrams illustrate the flow of interactions and messages between different components or objects within an +application. These diagrams are particularly useful for understanding the order of operations and the dependencies +between different parts of the system. For example, a sequence diagram for a Magento 2 checkout process might show the +interactions between the frontend, backend, and external payment gateway. + +## Common Components in PHP and Magento 2 Architecture Diagrams + +When creating architecture diagrams for PHP and Magento 2 applications, there are several common components that are +often included. Here are some examples: + +### 1. Frontend (Presentation Layer) + +The frontend component represents the user interface and the interactions between the user and the system. In PHP and +Magento 2 applications, this often includes HTML, CSS, JavaScript, and PHP templates. The frontend component +communicates with the backend to retrieve data and update the user interface. + +### 2. Backend (Application Layer) + +The backend component represents the logic and processing of the application. In PHP and Magento 2 applications, this +includes PHP classes, controllers, and services. The backend component interacts with the frontend to handle user +requests, process data, and retrieve data from the database. + +### 3. Database (Data Layer) + +The database component represents the storage and retrieval of data within the application. In PHP and Magento 2 +applications, common databases include MySQL or Magento's own database abstraction layer. The backend component +interacts with the database to store and retrieve data. + +### 4. External Services and APIs + +External services and APIs represent any external systems or services that the application interacts with. In PHP and +Magento 2 applications, this can include payment gateways, shipping providers, and third-party APIs. These services are +often represented as separate components in the architecture diagram and show the interactions between the application +and the external services. + +## Examples and Code Snippets + +To illustrate the concepts discussed above, here are some examples of architecture diagrams and code snippets that +represent the architecture of a PHP and Magento 2 application. + +**High-Level System Diagram:** + +``` ++------------------+ +-----------------+ +-----------------+ +| Frontend | | Backend | | Database | +| |<------>| |<------>| | +| HTML, CSS, JS | | PHP Classes | | MySQL/Magento | ++------------------+ +-----------------+ +-----------------+ +``` + +**Layered Architecture Diagram:** + +``` ++------------------+ +| Presentation | +| Layer | ++------------------+ +| Application | +| Layer | ++------------------+ +| Domain | +| Layer | ++------------------+ +| Data | +| Layer | ++------------------+ +``` + +**Component Diagram:** + +``` ++-----------------+ +| Frontend | +| Component | ++-----------------+ +| Backend | +| Component | ++-----------------+ +| Database | +| Component | ++-----------------+ +``` + +**Sequence Diagram:** + +``` +Frontend -> Backend: Request Product Details +Backend -> Database: Retrieve Product Data +Database --> Backend: Return Product Data +Backend --> Frontend: Render Product Details +``` + +## Conclusion + +Architecture diagrams are valuable tools for understanding and communicating the structure and components of a system. +In PHP and Magento 2 applications, architecture diagrams can help developers and stakeholders visualize the +relationships between modules, classes, and components. By using different types of architecture diagrams, such as +high-level system diagrams, layered architecture diagrams, component diagrams, and sequence diagrams, it is possible to +gain a deeper understanding of the system's design and identify potential issues. diff --git a/directory-structure.md b/directory-structure.md index e69de29..589f139 100644 --- a/directory-structure.md +++ b/directory-structure.md @@ -0,0 +1,77 @@ +# Directory Structure Documentation + +[TOC] + +## Introduction + +This documentation provides an in-depth understanding of the directory structure used in PHP and Magento 2 projects. A +well-organized and logical directory structure is crucial for efficient development and maintenance of complex +applications. By following the recommended structure, developers can easily locate, modify, and extend code while +adhering to best practices. This documentation will outline the main directories, their purposes, and provide specific +examples and code snippets to illustrate the concepts. + +## Root Directory + +The root directory of a PHP or Magento 2 project contains essential files and directories necessary for the project to +function. Let's examine the common files and directories found in this root directory: + +1. **app**: This directory contains the majority of your application code and configuration files. It is the heart of + the Magento 2 application and contains several subdirectories, including: + + - **code**: This directory is home to your custom PHP modules, organized by vendor name and module name. For + instance, if you have a module named "MyModule" developed by "MyVendor," the directory structure would + be `app/code/MyVendor/MyModule`. + + - **design**: This directory contains your theme-specific files, such as HTML templates, CSS stylesheets, and + JavaScript files. The structure follows the same pattern as the `code` directory, with themes organized by vendor + name and theme name. + + - **etc**: The `etc` directory holds configuration files for various aspects of your application, including module + configuration, database scripts, and system configuration settings. The structure mirrors the `code` directory, + with subdirectories for each module and theme. + + - **i18n**: This directory is used for internationalization (i18n) purposes. It contains translation files for + different languages, allowing your application to be easily localized. Translations are organized by module and + theme. + + - **view**: The `view` directory is where you define the front-end presentation of your application. It contains + subdirectories like `frontend` and `adminhtml` for different areas of your application. Each area has its own set + of directories for layout, templates, and web assets. + + - **vendor**: This directory is created when you install dependencies using Composer. It contains all the + third-party libraries and modules your project depends on. It is generally recommended not to modify files in this + directory directly. + + - **composer.json**: This file specifies the project's dependencies and other metadata required by Composer for + managing dependencies and autoloading. + + - **index.php**: The `index.php` file is the entry point of your Magento 2 application. It initializes the Magento + framework and processes incoming requests. + + - **.htaccess**: This file contains Apache web server configuration directives, such as URL rewrite rules and + security settings. It helps control access to files and directories. + +2. **bin**: This directory contains command-line scripts used for various development tasks. For Magento 2 projects, it + includes useful scripts like `magento` for running CLI commands and `setup` for installing and upgrading the + application. + +3. **dev**: The `dev` directory is used for development-specific tools and configurations. It may contain additional + scripts, debugging utilities, or profiling tools. + +4. **pub**: This directory houses publicly accessible files that are served directly by the web server. It includes + files like images, stylesheets, and JavaScript that can be accessed by users. Magento places its static assets in + directories like `static`, `media`, and `frontend`. + +5. **var**: This directory is used for storing various types of data generated by the application at runtime. It + typically includes log files, compiled code, caches, sessions, and generated static files. You should ensure this + directory is writable by the web server. + +6. **vendor**: Similar to the `vendor` directory in the `app` directory, this directory contains all the third-party + libraries and modules your project depends on. It is managed by Composer and should not be modified directly. + +## Conclusion + +Understanding the directory structure of a PHP or Magento 2 project is crucial for efficient development and +maintenance. By following the recommended structure outlined in this documentation, developers can easily navigate and +manage their codebase, resulting in a more organized and maintainable application. Use the provided examples and code +snippets to gain a deeper understanding of the concepts discussed. Happy coding! diff --git a/documentation.md b/documentation.md index 16b294c..d10e17d 100644 --- a/documentation.md +++ b/documentation.md @@ -65,38 +65,36 @@ - [Reporting security issues](/docs/{{version}}/reporting-security-issues) - ## Performance & Scalability - [Performance best practices](/docs/{{version}}/performance-best-practices) - - [Caching in Magento 2](/docs/{{version}}/caching-in-magento-2) - - [Scalability options and recommendations](/docs/{{version}}/scalability-options-and-recommendations) + - [Scalability options](/docs/{{version}}/scalability-options-and-recommendations) - ## Deployment & DevOps - - [Recommended development workflows](/docs/{{version}}/recommended-development-workflows) - - [Continuous Integration/Continuous Deployment (CI/CD) with Magento 2](/docs/{{version}}/ci-cd) - - [Server setup and configuration](/docs/{{version}}/server-setup-and-configuration) + - [Development workflows](/docs/{{version}}/recommended-development-workflows) + - [CI/CD with Magento 2](/docs/{{version}}/continious-integration-continious-deployment) + - [Server setup](/docs/{{version}}/server-setup-and-configuration) - ## Tutorials & Examples - [Collection of real-world examples, and step-by-step tutorials](/docs/{{version}}/collection-of-real-world-examples-and-step-by-step-tutorials) - [Case studies of problem-solving in Magento 2](/docs/{{version}}/case-studies-of-problem-solving-in-magento-2) - ## Community & Support - - [How to get help and support](/docs/{{version}}/how-to-get-help-and-support) - - [How to contribute to the Magento 2 community](/docs/{{version}}/how-to-contribute-to-the-magento-2-community) + - [Get help and support](/docs/{{version}}/how-to-get-help-and-support) + - [Community Contribution](/docs/{{version}}/how-to-contribute-to-the-magento-2-community) - ## File References - - [acl.xml](/docs/{{version}}/acl-xml) - - [cache.xml](/docs/{{version}}/cache-xml) - - [cron_groups.xml](/docs/{{version}}/cron-groups-xml) - - [cron_jobs.xml](/docs/{{version}}/cron-jobs-xml) - - [db_schema.xml](/docs/{{version}}/db-schema-xml) - - [di.xml](/docs/{{version}}/di-xml) - - [email_templates.xml](/docs/{{version}}/email-templates-xml) - - [events.xml](/docs/{{version}}/events-xml) - - [events.xml](/docs/{{version}}/events-xml) - - [extension_attributes.xml](/docs/{{version}}/extension-attributes-xml) - - [fieldset.xml](/docs/{{version}}/fieldset-xml) - - [indexer.xml](/docs/{{version}}/indexer-xml) - - [layout.xml](/docs/{{version}}/layout-xml) - - [menu.xml](/docs/{{version}}/menu-xml) - - [routes.xml](/docs/{{version}}/routes-xml) - - [system.xml](/docs/{{version}}/system-xml) - - [view.xml](/docs/{{version}}/view-xml) - - [webapi.xml](/docs/{{version}}/webapi-xml) - - [widget.xml](/docs/{{version}}/widget-xml) + - [acl.xml](/docs/{{version}}/acl_xml) + - [cache.xml](/docs/{{version}}/cache_xml) + - [cron_jobs.xml](/docs/{{version}}/cron_jobs_xml) + - [cron_groups.xml](/docs/{{version}}/cron_groups_xml) + - [db_schema.xml](/docs/{{version}}/db_schema_xml) + - [di.xml](/docs/{{version}}/di_xml) + - [email_templates.xml](/docs/{{version}}/email_templates_xml) + - [events.xml](/docs/{{version}}/events_xml) + - [extension_attributes.xml](/docs/{{version}}/extension_attributes_xml) + - [fieldset.xml](/docs/{{version}}/fieldset_xml) + - [indexer.xml](/docs/{{version}}/indexer_xml) + - [layout.xml](/docs/{{version}}/layout_xml) + - [menu.xml](/docs/{{version}}/menu_xml) + - [routes.xml](/docs/{{version}}/routes_xml) + - [system.xml](/docs/{{version}}/system_xml) + - [view.xml](/docs/{{version}}/view_xml) + - [webapi.xml](/docs/{{version}}/webapi_xml) + - [widget.xml](/docs/{{version}}/widget_xml) - ## References - [Glossary of terms](/docs/{{version}}/glossary-of-terms) - [Magento 2 coding standards](/docs/{{version}}/magento-2-coding-standards) diff --git a/email-templates-xml.md b/email-templates-xml.md deleted file mode 100644 index e69de29..0000000 diff --git a/email-templates.md b/email-templates.md index e69de29..a7830ab 100644 --- a/email-templates.md +++ b/email-templates.md @@ -0,0 +1,185 @@ +# Email Templates Documentation + +[TOC] + +## Introduction + +Email templates are an essential part of any application that requires sending automated emails. In the context of +Magento 2, email templates play a crucial role in providing a standardized format for sending transactional emails to +customers, such as order confirmation, shipment details, and password reset notifications. This documentation aims to +guide developers on how to create and customize email templates in Magento 2 using PHP. + +## 1. Creating Email Templates + +Magento 2 provides a straightforward way to create email templates. These templates define the structure and content of +the email being sent. Email templates are stored in the `app/design/frontend/{Vendor}/{Theme}/Magento_Email/email/` +directory of your Magento installation. + +To create a new email template, follow these steps: + +1. In your theme directory, create the `email` directory if it doesn't already exist. +2. Create a new `.html` file corresponding to the email template you want to create. For + example, `order_confirmation.html` for the order confirmation email. +3. Open the file and define the HTML structure of your email. You can use inline CSS or include external CSS files. +4. Add placeholders using the following syntax: `{{var placeholder_name}}`. These placeholders will be replaced with + dynamic content when the email is sent. + +Example of a basic email template: + +```html + + + + + +

Order Confirmation

+

Dear {{var customer_name}},

+

Your order {{var order_increment_id}} has been confirmed.

+ + +``` + +## 2. Customizing Email Templates + +Magento 2 allows you to customize the existing email templates or create new ones based on your specific requirements. +To customize an email template: + +1. Identify the email template you wish to modify. Magento provides a list of predefined templates, such + as `sales_email_order_template`, `sales_email_shipment_template`, etc. +2. In your theme directory, create the `email` directory if it doesn't already exist. +3. Copy the desired email template file from `vendor/magento/module-email/view/frontend/email/` + to `app/design/frontend/{Vendor}/{Theme}/Magento_Email/email/`. +4. Modify the copied email template as per your requirements. + +Example of customizing an existing email template: + +```html + + + + + +

New Order Notification

+

Dear Admin,

+

A new order has been placed with the following details:

+ + +

Order ID: {{var order.increment_id}}

+

Order Total: {{var order.base_grand_total}}

+ +

Please take appropriate action.

+ + +``` + +## 3. Variables and Conditions + +Email templates in Magento 2 can utilize variables and conditions to dynamically populate content and control the flow +of the email. These variables provide access to various data associated with the email, such as customer information, +order details, etc. + +To use variables and conditions, wrap them in double curly braces (`{{ }}`). For example, `{{var customer_name}}` is a +variable that will be replaced with the actual customer name when the email is sent. + +Example of using variables and conditions in an email template: + +```html + + + + +

Order Confirmation

+ + +{{if customer.is_logged_in}} +

Dear {{var customer_name}},

+{{else}} +

Dear Valued Customer,

+{{/if}} + +

Your order {{var order_increment_id}} has been confirmed.

+ + + + + + + + {{foreach order.getItems() as item}} + + + + + {{/foreach}} +
ProductPrice
{{var item.name}}{{var item.price}}
+ + + +``` + +## 4. Rendering Email Templates + +Once you have created or customized an email template, you need to render it within your code to send the email. In +Magento 2, you can render email templates using the `Magento\Framework\Mail\Template\TransportBuilder` class. + +Example of rendering and sending an email using a custom template: + +```php +transportBuilder = $transportBuilder; + $this->storeManager = $storeManager; + } + + public function sendOrderConfirmationEmail($customerEmail, $order) + { + $templateOptions = [ + 'area' => Area::AREA_FRONTEND, + 'store' => $this->storeManager->getStore()->getId() + ]; + + $templateVars = [ + 'order' => $order, + 'customer' => [ + 'is_logged_in' => true, + 'name' => 'John Doe' + ] + ]; + + $from = [ + 'email' => 'sender@example.com', + 'name' => 'Sender Name' + ]; + + $this->transportBuilder->setTemplateIdentifier('order_confirmation') + ->setTemplateOptions($templateOptions) + ->setTemplateVars($templateVars) + ->setFrom($from) + ->addTo($customerEmail) + ->getTransport() + ->sendMessage(); + } +} + +``` + +## 5. Conclusion + +Email templates in Magento 2 are powerful tools for creating standard email formats and customizing their content. By +following the instructions provided in this documentation, you can create, customize, and render email templates that +meet your specific requirements. Remember to utilize variables and conditions to dynamically populate content and +control the flow of your emails. Happy coding! diff --git a/email_templates.md b/email_templates_xml.md similarity index 99% rename from email_templates.md rename to email_templates_xml.md index 95ce7c3..f9f97c7 100644 --- a/email_templates.md +++ b/email_templates_xml.md @@ -1,4 +1,6 @@ -# Email Templates XML Reference Documentation +# `email_templates.xml` Reference Documentation + +[TOC] This reference documentation provides detailed information on the structure and usage of the `email_templates.xml` file in Magento 2. It is intended for developers familiar with PHP and Magento 2, and aims to provide authoritative and diff --git a/events-xml.md b/events-xml.md deleted file mode 100644 index e69de29..0000000 diff --git a/events.md b/events.md index e69de29..d277cbe 100644 --- a/events.md +++ b/events.md @@ -0,0 +1,144 @@ +# Event Documentation + +[TOC] + +This documentation provides a comprehensive guide on events in Magento 2, specifically tailored for developers familiar +with PHP and Magento 2. Events in Magento 2 allow you to extend the functionality of the core system by injecting custom +code at specific points in the application flow. By understanding and utilizing events effectively, you can enhance the +flexibility and modularity of your Magento 2 stores. + +## Table of Contents + +1. [Introduction to Events](#introduction-to-events) +2. [Using Events in Magento 2](#using-events-in-magento-2) +3. [Event Dispatching](#event-dispatching) +4. [Event Observers](#event-observers) +5. [Creating Custom Events](#creating-custom-events) +6. [Summary](#summary) + +## Introduction to Events + +Events in Magento 2 follow the Observer design pattern, allowing you to observe and respond to specific events triggered +during the execution of the system. These events serve as hooks, enabling you to inject custom code before, during, or +after the execution of predefined processes. + +## Using Events in Magento 2 + +To understand how events work in Magento 2, let's explore a basic example. Suppose you want to add a custom logging +functionality whenever a new customer account is created. By leveraging events, you can achieve this without modifying +the core code. + +### Event Dispatching + +In Magento 2, events are dispatched using the `Magento\Framework\Event\ManagerInterface` interface. To dispatch an +event, you need to follow these steps: + +1. Determine the event name to be dispatched. In this example, we will use the event `customer_register_success`. + +2. Inject the `ManagerInterface` using dependency injection in your class: + +```php +protected $eventManager; + +public function __construct( + \Magento\Framework\Event\ManagerInterface $eventManager +) { + $this->eventManager = $eventManager; +} +``` + +3. Dispatch the event at the appropriate place in your code: + +```php +$this->eventManager->dispatch('customer_register_success', ['customer' => $customer]); +``` + +By dispatching the event `customer_register_success` and passing the `customer` object, we allow other observers to +react to this event. + +### Event Observers + +Observers are responsible for observing events and executing specific actions in response. Magento 2 provides a +convenient way to define observers using XML configuration. Let's create an observer for our example: + +1. Create a new XML file `events.xml` in your module's `etc` directory: + +```xml + + + + + + +``` + +2. Create the observer class `CustomLogger`: + +```php +namespace Vendor\Module\Observer; + +use Magento\Framework\Event\ObserverInterface; +use Psr\Log\LoggerInterface; + +class CustomLogger implements ObserverInterface +{ + protected $logger; + + public function __construct(LoggerInterface $logger) + { + $this->logger = $logger; + } + + public function execute(\Magento\Framework\Event\Observer $observer) + { + $customer = $observer->getData('customer'); + $this->logger->info('New customer registered: ' . $customer->getName()); + } +} +``` + +In this example, we observe the `customer_register_success` event and log a message containing the name of the customer +who registered using the `LoggerInterface`. + +### Creating Custom Events + +While Magento 2 provides a wide range of predefined events, you can also create custom events to fit your specific +needs. To create a custom event, follow these steps: + +1. Create a new XML file `events.xml` in your module's `etc` directory: + +```xml + + + + + + +``` + +2. Create the observer class `CustomObserver`: + +```php +namespace Vendor\Module\Observer; + +use Magento\Framework\Event\ObserverInterface; + +class CustomObserver implements ObserverInterface +{ + public function execute(\Magento\Framework\Event\Observer $observer) + { + // Custom logic goes here + } +} +``` + +In this example, we create a custom event named `custom_event` and associate it with the observer `CustomObserver`. + +## Summary + +Congratulations! You have learned the fundamentals of events in Magento 2. By dispatching and observing events, you can +extend the core functionality of the system without modifying the core code. This approach enhances modularity and +allows for easier maintenance and upgrades. Remember to refer to the official Magento 2 documentation for more detailed +information on specific events and their usage. Happy coding! diff --git a/events_xml.md b/events_xml.md new file mode 100644 index 0000000..465689a --- /dev/null +++ b/events_xml.md @@ -0,0 +1,101 @@ +# `events.xml` Reference Documentation + +[TOC] + +The `events.xml` file in Magento 2 is crucial for creating and handling events within the system. This file is +responsible for defining the events and the observers which listen to these events. + +## Overview + +Magento 2's `events.xml` is typically located under the `etc` directory in a module. The directory structure is as +follows: + +```plaintext +app +└── code + └── Vendor + └── Module + └── etc + ├── events.xml + └── ... +``` + +## File Structure + +The `events.xml` file uses XML format and generally follows this structure: + +```xml + + + + + + +``` + +- `event_name` refers to the event's unique name, which will be dispatched by Magento. +- `observer_name` is the unique name of the observer in the context of this event. +- `Vendor\Module\Observer\ObserverClass` is the class responsible for handling the event when it's triggered. +- `method` is the method in the ObserverClass that will be called. + +## Defining an Event + +Defining an event in the `events.xml` file is as simple as adding an `event` tag with a unique `name` attribute. Here's +an example: + +```xml + + + + +``` + +In this case, the `catalog_product_save_after` event is defined, which will trigger after a product is saved. + +## Defining an Observer + +Defining an observer for the event involves adding an `observer` tag inside the `event` tag. The `instance` attribute +specifies the class that will handle this event, while the `method` attribute defines the method that will be called. + +```xml + + +``` + +Here, when the `catalog_product_save_after` event triggers, the `execute` method of +the `Vendor\Module\Observer\ProductSaveAfter` class will be called. + +## Observer Class + +An observer class typically extends `Magento\Framework\Event\ObserverInterface` and implements the `execute` method, +where the event logic resides. + +Here's a sample observer class: + +```php +getEvent()->getProduct(); + // Handle the event logic here + } +} +``` + +## Conclusion + +The `events.xml` file plays a crucial role in Magento 2's event-driven programming paradigm. It facilitates interaction +between modules and helps maintain code decoupling, making it easier to modify or extend the functionalities. By +mastering event and observer implementation in Magento 2, developers can build highly flexible and scalable ecommerce +solutions. \ No newline at end of file diff --git a/extension-attributes-xml.md b/extension-attributes-xml.md deleted file mode 100644 index e69de29..0000000 diff --git a/extension-use-cases.md b/extension-use-cases.md index e69de29..fd29936 100644 --- a/extension-use-cases.md +++ b/extension-use-cases.md @@ -0,0 +1,70 @@ +# Extension Use Cases Documentation + +[TOC] + +## Introduction + +This documentation provides an overview of the use cases for using extensions in Magento 2. It explains what extensions are, why they are important, and provides concrete examples and code snippets to illustrate the concepts discussed. This documentation assumes that you have some familiarity with programming, specifically PHP and Magento 2. + +## What are Extensions? + +Extensions, also known as modules, are a fundamental part of Magento 2's architecture. They allow you to add new features, modify existing functionality, and customize the behavior of your Magento store. Extensions can be created by Magento or third-party developers and are typically distributed as installable packages. + +Extensions follow a modular approach, where each extension represents a self-contained unit of functionality. This modular design allows for easy customization and flexibility, as different extensions can be added or removed without affecting the core functionality of Magento. + +## Why Use Extensions? + +Using extensions in Magento 2 offers several benefits, including: + +1. **Increased functionality**: Extensions allow you to extend the core functionality of Magento, adding new features and capabilities to your store. For example, you can use an extension to integrate your store with a popular payment gateway or add a new shipping method. + +2. **Customization**: Extensions enable you to customize the behavior and appearance of your Magento store to align with your specific business requirements. You can modify existing functionality or create completely new functionality using extensions. + +3. **Time and cost savings**: By leveraging existing extensions, you can save valuable development time and reduce costs. Rather than building everything from scratch, you can take advantage of pre-built extensions that already provide the functionality you need. + +4. **Community-driven innovation**: The Magento community is vibrant and active, with a vast ecosystem of developers constantly creating and maintaining extensions. By using extensions, you can tap into this community-driven innovation and leverage the work of other developers. + +## Use Cases + +Here are a few common use cases for using extensions in Magento 2, along with code snippets to illustrate the concepts: + +### Payment Gateway Integration + +Many extensions provide integration with popular payment gateways, allowing you to accept payments from various providers. For example, let's say you want to add support for the Stripe payment gateway. You can install the "Stripe Payment" extension, which provides the necessary integration code. Once installed, you can configure the extension and start accepting payments through Stripe. + +```php +// Code snippet to configure the Stripe Payment extension +$stripeApiKey = 'your-api-key'; +$stripePaymentConfig = $this->getConfig('payment/stripe'); +$stripePaymentConfig->setApiKey($stripeApiKey); +``` + +### Product Recommendations + +Extensions can also be used to enhance your store's product recommendation capabilities. Suppose you want to improve the product suggestion algorithm on your homepage. You can install an extension like "Product Recommendations Pro," which offers advanced recommendation algorithms. After installation, you can configure the extension to customize the recommendation logic and display personalized product suggestions to your customers. + +```php +// Code snippet to display personalized product recommendations +$recommendedProducts = $this->getRecommendedProducts('homepage'); +foreach ($recommendedProducts as $product) { + echo $product->getName(); + echo $product->getPrice(); + // Display other product details +} +``` + +### Storefront Customization + +Extensions also enable you to customize the appearance and behavior of your storefront. Let's say you want to change the layout and styling of the product listing page. You can install an extension like "Custom Product Listing Layout" and use its configuration options to modify the layout and styling of the product listing page. + +```php +// Code snippet to modify the product listing layout +$productListingConfig = $this->getConfig('custom_product_listing'); +$productListingConfig->setColumnCount(4); +$productListingConfig->setShowPrice(true); +$productListingConfig->setShowAddToCartButton(false); +``` + +## Conclusion + +Extensions are a powerful tool in Magento 2 that allow you to extend the core functionality, customize your store, and enhance its capabilities. By leveraging existing extensions, you can save time and effort while benefiting from the constant innovation of the Magento community. Use the provided code snippets and examples to explore various use cases and start enhancing your Magento store today. diff --git a/extension_attributes.md b/extension_attributes.md new file mode 100644 index 0000000..d71a000 --- /dev/null +++ b/extension_attributes.md @@ -0,0 +1,142 @@ +# Extension Attributes Reference Documentation + +[TOC] + +## Introduction + +Extension attributes in Magento 2 provide a way to extend the functionality of existing data structures, such as models +or entities, without modifying the original code. This allows developers to add custom data fields to existing objects, +enabling them to store additional information relevant to their specific business requirements. + +This reference documentation aims to provide a comprehensive overview of extension attributes in Magento 2, including +how to define, use, and manipulate them. By following the guidelines and examples provided, developers will be able to +effectively leverage extension attributes to enhance their Magento 2 projects. + +## 1. Defining Extension Attributes + +Extension attributes are defined in `extension_attributes.xml` files located in the `etc` directory of a module. These +XML files specify the structure and behavior of the extension attributes. Each `extension_attributes.xml` file can +define extension attributes for one or more data structures. + +To define an extension attribute, you need to specify its name, type, and the data structure it extends. +The `extension_attributes.xml` file follows a hierarchical structure, with a root `` element +containing individual `` elements for each attribute. + +Here's an example of an `extension_attributes.xml` file defining an extension attribute named `custom_attribute` for +the `Magento\Catalog\Api\Data\ProductInterface` data structure: + +```xml + + + + + + +``` + +In this example, the extension attribute `custom_attribute` is defined as a `string` type. It can now be used to store +additional custom data for products. + +## 2. Using Extension Attributes + +Once extension attributes are defined, they can be used to store and retrieve custom data for the data structures they +extend. To access an extension attribute, you need to use the corresponding getter and setter methods provided by the +Magento 2 framework. + +For instance, using the `custom_attribute` extension attribute defined in the previous example, you can retrieve and set +its value for a product object as follows: + +```php +/** @var Magento\Catalog\Api\Data\ProductInterface $product */ +$product->setCustomAttribute('custom_attribute', 'some value'); + +// Get the value of the extension attribute +$value = $product->getCustomAttribute('custom_attribute')->getValue(); +``` + +It is important to note that extension attributes are not automatically persisted to the database. You need to manually +save the object containing the extension attribute for the changes to take effect. + +## 3. Manipulating Extension Attributes + +Extension attributes can also be manipulated using plugins and observers. Plugins allow you to modify the behavior of +getter and setter methods, while observers enable you to react to changes in extension attribute values. + +To create a plugin for an extension attribute, you need to define a class that implements +the `Magento\Framework\Api\ExtensionAttributesInterface` interface. This class should contain the desired logic for the +plugin. + +Here's an example of a plugin that modifies the behavior of the `getCustomAttribute` method for the `custom_attribute` +extension attribute: + +```php +use Magento\Framework\Api\ExtensionAttributesInterface; + +class CustomAttributePlugin +{ + public function afterGetCustomAttribute( + ExtensionAttributesInterface $subject, + $result, + $attributeCode + ) { + // Modify the result based on custom logic + return $modifiedResult; + } +} +``` + +Observers, on the other hand, allow you to react to changes in extension attribute values by defining observers in the +module's `events.xml` file. These observers are triggered when extension attributes are modified, allowing you to +perform additional actions. + +## 4. Code Examples + +To provide further understanding and practical guidance, here are a few code examples showcasing the usage of extension +attributes in Magento 2: + +1. Retrieving and setting an extension attribute for a product: + +```php +/** @var Magento\Catalog\Api\Data\ProductInterface $product */ +$product->setCustomAttribute('custom_attribute', 'some value'); + +// Get the value of the extension attribute +$value = $product->getCustomAttribute('custom_attribute')->getValue(); +``` + +2. Creating a plugin for an extension attribute: + +```php +use Magento\Framework\Api\ExtensionAttributesInterface; + +class CustomAttributePlugin +{ + public function afterGetCustomAttribute( + ExtensionAttributesInterface $subject, + $result, + $attributeCode + ) { + // Modify the result based on custom logic + return $modifiedResult; + } +} +``` + +3. Defining an observer for extension attribute changes: + +```xml + + + + + + +``` + +In conclusion, extension attributes in Magento 2 offer a powerful way to extend existing data structures and store +additional custom data. By following the guidelines and examples provided in this reference documentation, developers +will be able to effectively leverage extension attributes in their Magento 2 projects, enhancing the flexibility and +functionality of their applications. diff --git a/extension_attributes_xml.md b/extension_attributes_xml.md new file mode 100644 index 0000000..33871c9 --- /dev/null +++ b/extension_attributes_xml.md @@ -0,0 +1,90 @@ +# `extension_attributes.xml` Reference Documentation + +[TOC] + +The `extension_attributes.xml` file is an essential part of Magento 2, providing a robust way to extend Magento service +contracts' data. Extension attributes are custom attributes that are added to entities such as products, orders, +customers, etc. + +## Overview + +The `extension_attributes.xml` file is typically located under the `etc` directory in a module: + +```plaintext +app +└── code + └── Vendor + └── Module + └── etc + ├── extension_attributes.xml + └── ... +``` + +## File Structure + +The structure of the `extension_attributes.xml` file in Magento 2 follows this pattern: + +```xml + + + + + + +``` + +- `for` specifies the interface for which the extension attribute is added. +- `code` is the unique name for the extension attribute. +- `type` is the data type for the extension attribute. + +## Defining Extension Attributes + +Defining an extension attribute requires specifying the `for` attribute, which mentions the Interface against which we +are defining the attribute. The `code` and `type` define the attribute itself. + +Here is an example of adding a custom attribute to the Product entity: + +```xml + + + + +``` + +## Accessing Extension Attributes + +Extension attributes can be accessed and set via the entity's extension attributes object. Here's an example using the +product entity: + +```php +productRepository->get('product_sku'); +$extensionAttributes = $product->getExtensionAttributes(); + +// Get the value of the custom_attribute +$customAttributeValue = $extensionAttributes->getCustomAttribute(); + +// Set a value for the custom_attribute +$extensionAttributes->setCustomAttribute('New Value'); +$product->setExtensionAttributes($extensionAttributes); + +$this->productRepository->save($product); +``` + +## Best Practices + +1. Extension attributes should be added for service contract interfaces only. Do not use them for other classes or + interfaces. + +2. It's best not to use extension attributes as a substitute for custom attributes. Use them when you need to add data + to an entity that does not naturally belong to it. + +3. Keep in mind that extension attributes are not persisted automatically. Developers need to handle the persistence ( + saving/loading) of these attributes manually. + +## Conclusion + +The `extension_attributes.xml` file is a powerful tool in Magento 2, enabling developers to extend data for service +contract interfaces. Proper understanding and usage of extension attributes contribute to building flexible and +extendable custom modules. diff --git a/fieldset-xml.md b/fieldset-xml.md deleted file mode 100644 index e69de29..0000000 diff --git a/fieldset_xml.md b/fieldset_xml.md new file mode 100644 index 0000000..26bce62 --- /dev/null +++ b/fieldset_xml.md @@ -0,0 +1,181 @@ +# `fieldset.xml` Reference Documentation + +[TOC] + +## Introduction + +The `fieldset.xml` file is an important configuration file in the Magento 2 framework. It is used to define and modify +the structure of data fields retrieved from database tables and models. This documentation will guide you through the +different elements and attributes used in `fieldset.xml` and their corresponding functionalities. By understanding and +correctly using `fieldset.xml`, you can customize and extend the data fields in your Magento 2 application. + +## File Structure + +The `fieldset.xml` file follows a specific structure that consists of one or more `
` elements. +Each `
` element can contain one or more `` elements, and each `` element can contain one +or more `` elements. Here is an example of the basic structure of a `fieldset.xml` file: + +```xml + +
+ + + +
+``` + +Throughout this documentation, we will examine each element and attribute in detail, providing examples and code +snippets to illustrate their usage. + +## Element: fieldset + +The `
` element is the root element of the `fieldset.xml` file. It is used to define a group of data fields. +Each `fieldset.xml` file can contain multiple `
` elements. Here is an example of a `fieldset.xml` file with +multiple `
` elements: + +```xml + +
+ +
+ +
+ +
+``` + +## Element: container + +The `` element is used to group related fields together within a `
`. It provides a way to organize +and structure the fields. Each `` element can contain one or more `` elements. Here is an example of +a `fieldset.xml` file with a `` element: + +```xml + +
+ + + + +
+``` + +## Element: field + +The `` element is used to define a data field within a ``. It specifies the name, sort order, and +component of the field. The name attribute is mandatory, while the sortOrder and component attributes are optional. Here +is an example of a `fieldset.xml` file with a `` element: + +```xml + +
+ + + +
+``` + +## Attribute: name + +The `name` attribute is used to specify the name of a `` or ``. It serves as a unique identifier for +the container or field within the `fieldset.xml` file. The name should be a string without spaces or special characters. +For example, a field with the name "first_name" can be defined as follows: + +```xml + +
+ + + +
+``` + +## Attribute: sortOrder + +The `sortOrder` attribute is used to specify the order in which fields are rendered within a ``. Fields with +lower `sortOrder` values will be rendered before fields with higher `sortOrder` values. The `sortOrder` attribute is +optional, and if not specified, fields will be rendered in the order they are defined in the `fieldset.xml` file. Here +is an example of a `fieldset.xml` file with fields sorted using the `sortOrder` attribute: + +```xml + +
+ + + + +
+``` + +## Attribute: component + +The `component` attribute is used to specify the JavaScript component that will render the field in the user interface. +The component determines the behavior and appearance of the field. The value of the `component` attribute should be a +valid JavaScript component path. Here is an example of a `fieldset.xml` file with a field component specified: + +```xml + +
+ + + +
+``` + +## Example Usage + +To illustrate the usage of `fieldset.xml`, let's consider an example where we want to add a custom field named "age" to +the "customer_account_edit" form. We can achieve this by creating a `fieldset.xml` file in our custom module with the +following content: + +```xml + +
+ + + +
+``` + +After creating the `fieldset.xml` file, we need to declare it in the module's `di.xml` file as follows: + +```xml + + + + \Magento\Customer\Block\Form::FORM_CODE_EDIT + + + + data + admin__fieldset-form + fieldset_form + + + + + + 70 + age + Age + Magento_Ui/js/form/element/input + + + + + + + + +``` + +In this example, the `` element is named "customer", and it contains a single `` element with the +name "age". The "age" field is rendered using the "Magento_Ui/js/form/element/input" JavaScript component. + +By following the above steps, the "age" field will be added to the customer account edit form in the Magento 2 backend. + +## Conclusion + +`fieldset.xml` is a powerful configuration file in Magento 2 that allows you to customize and extend the data fields in +your application. By understanding the elements and attributes in `fieldset.xml`, you can control the structure and +behavior of your data fields. diff --git a/functional-testing.md b/functional-testing.md index e69de29..a0f59eb 100644 --- a/functional-testing.md +++ b/functional-testing.md @@ -0,0 +1,112 @@ +# Functional Testing Documentation + +[TOC] + +## 1. Introduction + +Functional testing is a crucial aspect of software development, ensuring that the software meets the specified +functional requirements. This documentation aims to provide a comprehensive guide on performing functional testing using +PHP and Magento 2. + +Functional testing involves testing the individual functions or features of an application to ensure they work correctly +and meet the expected behavior. It focuses on validating the application's behavior against the defined requirements. + +## 2. Test Environment Setup + +Before starting the functional testing, it is essential to set up the test environment properly. Here are the steps to +follow: + +1. Install and configure Magento 2: Set up a local instance of Magento 2 for testing purposes. Follow the official + Magento 2 installation documentation for detailed instructions. + +2. Install and configure PHPUnit: PHPUnit is a popular testing framework for PHP. Install PHPUnit globally or as a + project dependency using Composer. Create a `phpunit.xml` file in the project root directory to configure PHPUnit. + Refer to the PHPUnit documentation for more details. + +3. Prepare test data: Create sample data or utilize existing data to ensure meaningful tests. For example, if testing an + e-commerce website, create test products, customers, and orders for various scenarios. + +## 3. Test Case Design + +Test case design is a critical phase in functional testing. Well-designed test cases ensure comprehensive coverage and +effective validation of the application's functionality. Here's how to design effective test cases: + +1. Identify test scenarios: Analyze the requirements and identify different scenarios that need to be tested. For + instance, if testing an e-commerce website, scenarios may include adding products to the cart, updating the cart + quantity, and placing an order. + +2. Define test steps: Break down each scenario into a series of steps. Be specific and detailed in defining the steps to + ensure reproducibility. + +3. Create test data: Determine the necessary data for each test case. This may involve creating or manipulating existing + data to execute the test steps successfully. + +4. Write test assertions: Define the expected outcomes for each test case. Assertions should be clear and concise, + defining what should be true after executing the test steps. + +```php +// Example test case using PHPUnit and Magento 2 +public function testAddToCart() +{ + // Step 1: Go to the product page + $this->browser->navigateTo('/product-page'); + + // Step 2: Add the product to the cart + $this->browser->click('.add-to-cart-button'); + + // Step 3: Check if the cart page is loaded + $this->browser->assertPageLoaded('/cart'); + + // Assertion: Verify that the product was added to the cart + $this->browser->assertElementExists('.cart-product'); +} +``` + +## 4. Test Execution + +Once the test cases are designed, it's time to execute them to validate the application's functionality. Follow these +steps for successful test execution: + +1. Run PHPUnit: Execute PHPUnit from the command line, specifying the test suite or individual test cases to run. The + test execution will begin, and PHPUnit will display the progress and test results. + +```bash +$ vendor/bin/phpunit --testsuite MyTestSuite +``` + +2. Monitor test execution: Keep an eye on the test execution process to identify any failures or errors. PHPUnit + provides detailed error messages and stack traces to aid in debugging. + +3. Debug and fix failures: In case of test failures, investigate the cause by analyzing the error messages and stack + traces. Fix the underlying issues in the application code or test cases to resolve the failures. + +4. Rerun failed tests: After fixing the failures, rerun the failed test cases to ensure they pass. This ensures the + stability and reliability of the tests. + +## 5. Test Reporting + +Proper test reporting is crucial for record-keeping and identifying trends in test results. Use the following approaches +for effective test reporting: + +1. Generate test reports: PHPUnit generates test reports in various formats, including HTML, XML, and JSON. Choose the + format that suits your needs and generate the reports after each test execution. + +```bash +$ vendor/bin/phpunit --log-junit test-results.xml +``` + +2. Analyze test results: Review the test reports to identify patterns, track progress, and identify any areas that need + improvement. Look for failing test cases, error rates, and trends in test execution times. + +3. Integrate with CI/CD pipelines: If using a continuous integration or delivery pipeline, integrate the test reports + for automated tracking and analysis. This allows you to monitor the test results over time and ensure ongoing quality + assurance. + +## 6. Conclusion + +Functional testing is crucial for ensuring the proper functioning of software applications. By following the steps +outlined in this documentation, you can effectively design, execute, and report on functional tests using PHP and +Magento 2. + +Remember to continually enhance your test suite, incorporating new scenarios and edge cases as the application evolves. +This will help maintain a high level of quality and ensure that the application meets user expectations. diff --git a/glossary-of-terms.md b/glossary-of-terms.md index e89be78..3543e4a 100644 --- a/glossary-of-terms.md +++ b/glossary-of-terms.md @@ -1,794 +1,140 @@ -- [A](#A) - - [above the fold](#above the fold) - - [active branch](#active branch) - - [adapter](#adapter) - - [admin](#admin) - - [Admin area](#Admin area) - - [ADMIN variables](#ADMIN variables) - - [adminhtml](#adminhtml) - - [area](#area) - - [attribute](#attribute) - - [attribute group](#attribute group) - - [attribute set](#attribute set) - - [average inventory cost](#average inventory cost) -- [B](#B) - - [base currency](#base currency) - - [batch processing](#batch processing) - - [block](#block) - - [brand](#brand) - - [brick-and-mortar](#brick-and-mortar) - - [bulk operations](#bulk operations) - - [bundle product](#bundle product) - - [bundled extension](#bundled extension) -- [C](#C) - - [cache backend](#cache backend) - - [cache frontend](#cache frontend) - - [cache type](#cache type) - - [capture](#capture) - - [cardholder](#cardholder) - - [cart rules](#cart rules) - - [catalog](#catalog) - - [catalog rules](#catalog rules) - - [category](#category) - - [checkout](#checkout) - - [cloud variables](#cloud variables) - - [CMS block](#CMS block) - - [complex data](#complex data) - - [component](#component) - - [configurable product](#configurable product) - - [conversion rate](#conversion rate) - - [core tier scaling](#core tier scaling) - - [credit memo](#credit memo) - - [credit memo comment](#credit memo comment) - - [credit memo item](#credit memo item) - - [cross-sell](#cross-sell) - - [CVM](#CVM) -- [D](#D) - - [database schema](#database schema) - - [dependency injection](#dependency injection) - - [deploy key](#deploy key) - - [double opt-in](#double opt-in) - - [downloadable product](#downloadable product) - - [dynamic content](#dynamic content) - - [dynamic media URL](#dynamic media URL) -- [E](#E) - - [ece-tools package](#ece-tools package) - - [entity](#entity) - - [entity attribute value](#entity attribute value) - - [evergreen content](#evergreen content) - - [extension](#extension) - - [extension attribute](#extension attribute) -- [F](#F) - - [freight on board](#freight on board) - - [frontend](#frontend) - - [frontend properties](#frontend properties) - - [fulfillment](#fulfillment) -- [G](#G) - - [gift card](#gift card) - - [gross margin](#gross margin) - - [grouped product](#grouped product) -- [H](#H) - - [handle](#handle) - - [horizontal scaling](#horizontal scaling) -- [I](#I) - - [interception](#interception) -- [L](#L) - - [layout](#layout) - - [layout instructions](#layout instructions) - - [layout update](#layout update) - - [License Owner](#License Owner) -- [M](#M) - - [MAGEID](#MAGEID) - - [markup](#markup) - - [master environment](#master environment) - - [merchant account](#merchant account) - - [MFTF](#MFTF) - - [module](#module) -- [O](#O) - - [OMS](#OMS) - - [origin cloaking](#origin cloaking) -- [P](#P) - - [Page Builder](#Page Builder) - - [payment gateway](#payment gateway) -- [R](#R) - - [related product](#related product) -- [S](#S) - - [sales rules](#sales rules) - - [scope](#scope) - - [service contract](#service contract) - - [settlement](#settlement) - - [Shared Catalog](#Shared Catalog) - - [shipment](#shipment) - - [shipment document](#shipment document) - - [shipping carrier](#shipping carrier) - - [shopping cart](#shopping cart) - - [simple product](#simple product) - - [SKU](#SKU) - - [splash page](#splash page) - - [static block](#static block) - - [static content](#static content) - - [static files](#static files) - - [store](#store) - - [store view](#store view) - - [storefront](#storefront) -- [T](#T) - - [tax rule](#tax rule) - - [template](#template) - - [theme](#theme) -- [U](#U) - - [UI component](#UI component) - - [UPWARD](#UPWARD) -- [V](#V) - - [Vendor Bundled Extension](#Vendor Bundled Extension) - - [vertical scaling](#vertical scaling) - - [virtual product](#virtual product) - - [virtual type](#virtual type) -- [W](#W) - - [website](#website) - - [widget](#widget) - - - -## A - -### above the fold -In a browser window, the content that is immediately visible after a web page loaded and before a user scrolled down the page. -When designing your layout, use flexible formats to best display the highest priority products, features, sales, notifications, options, and so on, in this area. -With mobile and tablets, the area of above the fold greatly differs, especially on the size and dimensions of the screen and orientation when viewing (portrait vs landscape). -Using responsive themes and testing can help find the right mix of content and layout. - - -### active branch -An active branch or environment is one that is connected to a deployed or running instance with access to services. -When you deactivate, the connection to the services and to the running instance is removed, but the code is preserved. -It becomes an ordinary git branch. - - -### adapter -A class that enables two otherwise incompatible systems to work together without modifying the systems’ source code. -Examples include database adapters, cache adapters, filesystem adapters, post-processor libraries adapters, and other types of computing adapters. - - -### admin -In software, a user role with full administrator privileges to manage all functionality. -In Mage-OS, admin users have full permissions and access to all features, options, and capabilities in the Admin. -They can also create users and roles. - - -### Admin area -The password-protected back office of your store where orders, catalog, content, and configurations are managed. -Users access the Admin area to manage the store, including products, orders, shipments, CMS content, design of the storefront, customer information, and so on. -Admin users have an associated role with permissions that controls access to features, options, and capabilities. - - -### ADMIN variables -ADMIN variables are project environment variables to override the configuration settings for the Admin user account to access the Admin UI. - - -### adminhtml -The internal area name assigned to the Admin. - - -### area -Area is an abstract term for a Mage-OS application scope. -Areas are logical components that organize code for optimized request processing. -Areas reduce the memory demands of configuration objects accessed from the storefront, and they streamline web service calls by loading only the required dependent code. -Each area can contain completely different code to process URLs and requests. - - -### attribute -A characteristic or property of a product that describes some aspect of the product. -Mage-OS or Mage-OS Open Source users can create custom attributes to add to the default attribute set or a custom attribute set. -Create these attributes through the Admin or programmatically. -Examples: color, size, weight, price, age, gender, and so on. -Custom attributes are a type of Entity-Attribute-Value (EAV) attribute. -For integrations like Google Shopping ads Channel and Amazon Sales Channel, you map Commerce attributes to attributes in the third-party to properly display and sell products, display ads. - - -### attribute group -A logical grouping of attributes within an attribute set. - - -### attribute set -A collection of attribute groups, customized for a specific product. -Example: A T-shirt attribute set might include color, size, gender, and brand. - - -### average inventory cost -Product price, less coupons, or discounts, plus freight and applicable taxes. -The average is determined by adding the beginning cost of inventory each month, plus the ending cost of inventory for the last month of the period. - - -## B - -### base currency -The primary currency that is used per store view for all online payments. -Stores can accept currencies from more than 200 countries around the world. -The store front provides a currency selector for multiple accepted currencies for a specific country or locale. -Currency symbols appear in product prices and sales documents such as orders and invoices. -You can customize the currency symbols as needed and set the display of the price separately for each store or view. - - -### batch processing -To perform a task or change multiple items all at once, without manual repetition. - - -### block -A unit of page output that renders some distinctive content - a piece of information, a user interface element - anything visually tangible for the end-user. -Blocks are implemented and provided by modules. Blocks use templates to generate HTML. -Examples of blocks include a category list, a mini cart, product tags, and product listing. -Dynamic blocks provide content based on logic, such as price rules. -Page Builder expands on the interactivity and creation of blocks and dynamic blocks. - - -### brand -A unique identity that defines a particular product or group of products by the manufacturer or Designer. -These include name brands for clothing, appliances, luxury items, and so on. -Your company may also be the brand, selling products under multiple brands based on the business unit, target audience, and so on. -Use custom attributes to save brand information for products. -Some extensions and integrations may use or require a brand for your products, such as Google Shopping ads Channel and Amazon Sales Channel. - - -### brick-and-mortar -A retail business with a permanent physical location, as opposed to businesses that function virtually or solely through the internet. -For Inventory Management and Order Management, this store is a source for tracking product quantities, shipping orders, and supporting in-store pickup. - - -### bulk operations -Bulk operations are actions that are performed on a large scale. -Example bulk operations tasks include importing or exporting items, changing prices on a mass scale, and assigning products to a warehouse. - - -### bundle product -Lets customers assemble a “build your own” customizable product from various options and configurations. -Each item in the bundle is either a separate simple or virtual product. - - -### bundled extension -The code that extends or customizes Mage-OS behavior is considered a Bundled Extension. -It can include modules, themes, and language packs. - - -## C - -### cache backend -Stores cache records into a two-level backend system within Zend’s default framework. -A first-level cache is fast — for example, an APC or Memcached backend — but it is limited and does not support tagging and grouping of cache entries. -A second-level cache — for example, a file system or a Redis backend — is slower but supports tagging and grouping. - - -### cache frontend -Specifies what kind of data is stored in the cache backend. - - -### cache type -A cache stores data so that future calls for that data load faster. -Other types can be created and defined. - - -### capture -The process of converting an authorized order amount into a billable transaction. -Transactions cannot be captured until authorized, and authorizations cannot be captured until the goods or services have been shipped. - - -### cardholder -A person who is authorized by a financial institution to make purchases on a credit card account. - - -### cart rules -Price rules that are applied to the shopping cart and trigger an action in response to a set of conditions. -Used to create promotions. - - -### catalog -For merchants, the catalog represents their product inventory. -Within Mage-OS architecture, the catalog consists of categories, products, and product attributes. -Each Commerce store has only one product catalog, which is shared by all store views. -In a multi-store installation, each store can have a separate catalog, or share the catalog. -The current store catalog is determined by the default root category, visible to the user in the top navigation (main menu) of the store. -(The term “root category” may be confusing, because the “root category” isn’t really a category at all, but a container for the menu, which consists of categories and subcategories.) -You can create as many root categories as you want, but only one (the default) can be used at a time. - - -### catalog rules -Price rules that are applied to specific products and trigger an action in response to a set of conditions. -Used to create promotions. - - -### category -A group of products that have something in common. -The main menu of the store is organized into categories and subcategories of products. - - -### checkout -The process of gathering the payment and shipping information that is necessary to complete the purchase of items in the shopping cart. -After the customer reviews the information and submits the order, an email confirmation is sent to the customer. -Checkout has many options and configuration out-of-the-box and through extension. - - -### cloud variables -Cloud variables are environment variables specific to Mage-OS on cloud infrastructure and use the prefix. - - -### CMS block -A special variant of block that can only be created in the Admin and cannot be referenced through layout files. - - -### complex data -Data that is associated with multiple product options. - - -### component -Used to refer to a module, theme, or language package in Mage-OS. - - -### configurable product -A configurable product looks like a single product with drop-down lists of options for each variation. -Each option is actually a separate simple product with a unique SKU, which makes it possible to track inventory for each product variation. -To achieve a similar effect, a simple product can be used with custom options, but without the ability to track inventory for each variation. -Products with multiple options are sometimes referred to as composite products. -Although a configurable product uses more SKUs, and may initially take a little longer to set up, it can save you time in the end. -If you plan to grow your business, the configurable product type might be a better choice for a product with multiple options. -Example: T-shirts that are available in two colors and three sizes. -Six variants must be created as individual products (each with its own SKU). -Then, all variants are added to a configurable product where customers can choose the size and color, and then add it to their cart. - - -### conversion rate -The percentage of visitors who are converted into buyers. - - -### core tier scaling -Core tier scaling consists of three service nodes for data storage, cache and services, such as OpenSearch, Elasticsearch, MariaDB, Redis. - - -### credit memo -A document issued by the merchant to a customer to write off an outstanding balance because of overcharge, rebate, or return of goods. -The memo restores funds to the customer’s account. - - -### credit memo comment -Details why a credit memo amount was credited to the customer. - - -### credit memo item -An invoiced item for which a merchant creates a credit memo. - - -### cross-sell -A product that appears next to the shopping cart. -When a customer navigates to the shopping cart page, these products are displayed as cross-sells to the items already in the shopping cart. -They are similar to impulse buys, like magazines and candy at the cash registers in grocery stores. - - -### CVM -An abbreviation for “Cardholder Verification Method”. -A way to verify the identity of the customer by confirming a 3-digit or 4-digit credit card security code with the payment processor. - - -## D - -### database schema -The structure of data in a database. -Defines how data is organized and how data relationships are governed, including all constraints applied to the data. -A module can contain fragments of the database schema if that module has data that must be stored in the database. - - -### dependency injection -A software design pattern that allows a class to specify its dependencies without having to construct them. -This class delegates the responsibility of injecting the dependency to the calling class. -Used to make testing easier. -To define dependencies for classes, edit the di.xml configuration file. - - -### deploy key -A deploy key is your project SSH public key and enables read-only or read-write (if enabled) access to a Git repository. - - -### double opt-in -An email verification process that requires potential subscribers to complete a second step that confirms their intention to subscribe. - - -### downloadable product -A digitally downloadable product that consists of one or more files that are downloaded, such as an eBook, music, video, software application, or an update. -You can offer an album for sale and sell each song individually. -A downloadable product can deliver an electronic version of your product catalog. -Downloadable files can reside on your server or be provided as URLs to any other server or content delivery network. - - -### dynamic content -Content that is generated by code rather than read from a static template. -After dynamic content is initially rendered when a user visits a page, sometimes the content can be cached and reused without requiring another dynamic call upon a revisit. - - -### dynamic media URL -A URL address that is generated dynamically by the system to reference an image or other media. -The address links directly to assets stored on a server or a content delivery network. -To use a static URL, change the configuration setting. -However, if dynamic media URLs are included in your catalog when you disable the setting, each reference in your catalog becomes a broken link. -Links can be restored by again enabling dynamic media URLs. -Using dynamic media URLs can affect catalog search performance. -Code format: media url=“path/to/image.jpg” - - -## E - -### ece-tools package -A set of scripts and tools designed to manage and deploy the Commerce application. This package simplifies many Mage-OS on cloud infrastructure processes, including deploying to a Docker environment, managing crons, verifying -project configuration, and applying Adobe patches. - - -### entity -A unique unit or object in programming. -Contains attributes or parameters that can be modified. -Examples include staging — where an update can change entities such as price rules, products, or categories — and database records — where service contracts include data structures that are sent and received. - - -### entity attribute value -For database entities, a data model that efficiently encodes entities. -Stores the entity id, attribute name, and value as a triple, which allows new entity attribute names to be created at any time. -In encoding, the number of attributes that can be used to describe entities can scale extensively, but the number that applies to a given entity is minimized. -This data model is flexible, but can be slow. - - -### evergreen content -Content that has a long shelf life or content that can be reused. - - -### extension -Code that extends or customizes Mage-OS behavior. -You can optionally package and distribute an extension on Commerce Marketplace or another extension distribution system. -A Commerce extension can include modules, themes, and language packs. - - -### extension attribute -Extend functionality and often use more complex data types than custom attributes. These attributes do not appear on the GUI. - - -## F - -### freight on board -In international shipping, this term means that the receiving party is responsible for the shipping charges. -FOB can be based on the place of origin or destination, and be designated as either freight collect or freight prepaid. - - -### frontend -In a client-server application, there is the backend and frontend. -The frontend component, or client, is an interface that enables users to manipulate or interact with the underlying backend code. -Backend code runs on a server. -A user cannot directly access backend code. -A user interacts with the storefront, which in turn uses code running on the Commerce server. -Note: In the past, the storefront has been referred to as the “frontend”, and the Admin has been referred to as the “backend”. This usage is no longer supported. - - -### frontend properties -Properties that determine the presentation and behavior of an attribute from the standpoint of the customer in your store. - - -### fulfillment -The process of managing customer shipments. - - -## G - -### gift card -A prepaid card or gift certificate that can be used to make purchases in the store. -Each gift card is assigned a unique code which is entered at checkout. -The value of the gift card is reflected in the gift card account balance. -There are three types of gift cards: - -Gift cards are configurable, including options for product eligibility and selection of open or fixed amounts. -A gift card can also be redeemed by the store administrator on customer request when the order is being created in the backend. -Gift cards also help promotions, as store administrators can manually create the gift card accounts in the backend and send the gift card codes to the specific customer segment. -Gift cards can serve as a loyalty program targeted at the most active customers who make numerous purchases from the web store or a specific promotional campaign during the holidays. - - -### gross margin -The difference between the cost and price of a product. - - -### grouped product -A product type with several similar, standalone products grouped on a single page. -Can be offered with variations of a single product or by grouping them by season or theme to create a coordinated set. -Each product can be purchased separately, or as part of the group. -For example, for a knife that is available in four sizes, all four knives can be displayed within a grouped product page. -Customers can select the sizes they want and add them to the cart from this page. - - -## H - -### handle -Generally, a handle is a way to reference an object. -In Mage-OS, handles are used in many places, most commonly to identify a page. -For page handles, the handle name is derived from the URL, then used to locate and load the layout files for the referenced page. -For example, in the Customer module, there is a layout file called “view/frontend/layout/checkout_cart_index.xml”. -Here “frontend” is the area name and “checkout_cart_index” is the handle name, both of which are derived from the URL. - - -### horizontal scaling -Horizontal scaling (also known as scaling out) is the process of adding additional nodes or machines to your infrastructure to meet growing demand. - - -## I - -### interception -The process of injecting new code before, after, or around an existing public function of a PHP class. -To intercept a function, a plug-in implements the additional code to be invoked. -Plug-ins are associated with interception points by the dependency injection configuration file (di.xml). -If multiple plug-ins are defined on the same function, the dependency injection configuration defines the order in which the plug-ins are invoked, allowing multiple plug-ins to be used without conflict. - - -## L - -### layout -In the construction of a Commerce page, a layout is a series of blocks assembled in a hierarchy, representing the structure of the page. -Page layout files focus on the highest level of page structure (header, footer, main content area, left sidebar, and so on). -Layout files then assemble content (blocks) into these different areas on the page. - - -### layout instructions -Markup in a layout file that describes changes to be applied to a structured element tree of blocks, containers, and UI components. -A single layout file can contain multiple layout instructions. -Layout instructions are encoded in XML in layout files. - - -### layout update -Used for snippets of code that are added to modify the XML layout or to import the layout instructions from another file. - - -### License Owner -The License Owner (also known as Account Owner) is the designated person in a business organization that manages payments and other business-related issues for the Mage-OS on cloud infrastructure account. -This person serves as the point of contact with Adobe. -After a business purchases an Mage-OS on cloud infrastructure subscription, initial project and code access is available only to the person designated as the License Owner. - - -## M - -### MAGEID -MAGEID is typically the billing contact on the Mage-OS account (and may not be the Project Owner of the Mage-OS on cloud infrastructure project). -For access entitlement to Mage-OS and Mage-OS on cloud infrastructure packages, you must use access keys associated with a MAGEID that has been granted access to those packages. - - -### markup -In marketing and retail, a percentage added to the cost of an item to determine the retail price. -Configure the markup, or markdown, of a product through product customizable options. -In development, a computer language that controls the processing, presentation, and formatting of text. -Also, markup tags are snippets of code that add functionality or content to a CMS page or block. - - -### master environment -On Mage-OS on cloud infrastructure, Pro projects use an active Platform as a Service (PaaS) environment called master that includes a copy of your Production environment database and web server. - - -### merchant account -An account with a bank or financial institution that makes it possible to accept credit card transactions. - - -### MFTF -MFTF is a Functional Testing Framework. -It provides a testing framework for Commerce developers and software engineers, such as QA specialists, PHP developers, and system integrators. -Developers and QA can write tests to attempt user interactions with web applications, verify functionality, and automate regression testing. - - -### module -Code that changes or extends features provided by the Mage-OS application. -A module is contained in a directory structure that contains PHP and XML files (configuration, blocks, controllers, helpers, models, and so on) related to a specific functionality to deliver a distinct collection of product -features. -The purpose of each module is to provide specific product features by implementing new functionality or extending the functionality of other modules. -Each module is designed to function independently, so the inclusion or exclusion of a particular module does not impact the functionality of other modules. -A module can also implement widgets, which are page elements that can be customized by business users in the Admin. -Modules can be disabled or removed without breaking the consistency of the Mage-OS application. -One exception: When the module depends on other modules, which requires disabling or removing the dependent modules. - - -## O - -### OMS -OMS is Adobe’s Order Management System offering. -OMS is a flexible and affordable solution for managing, selling, and fulfilling inventory from any sales channel. -OMS provides a seamless customer experience, which increases sales while reducing costs, and accelerates the time to market. -OMS capabilities include: - - -### origin cloaking -Origin cloaking is a security feature that allows Mage-OS on cloud infrastructure to block any non-Fastly traffic to prevent DDoS attacks, going to the cloud infrastructure (origin). - - -## P - -### Page Builder -Page Builder is a Commerce extension for creating content-rich pages by dragging and dropping pre-built controls to define custom layouts. -These controls are also known as “content types”. -Merchants can design layouts and pages without coding experience. -Extension support is provided for developers to extend Page Builder. - - -### payment gateway -A payment gateway is a third-party service that seamlessly processes credit card transactions without the customer leaving the merchant’s site. - - -## R - -### related product -A selection of products that is presented as an incentive to purchase additional items. -For example, if the customer is viewing the product page for a camera, the related products might include other comparable cameras, a camera case, and a tripod. - - -## S - -### sales rules -Includes cart and catalog rules, which are used to price a product for promotions. - - -### scope -In Mage-OS, scope describes the extent of your store hierarchy that a setting can affect. -Scope can apply to the following: -Within the hierarchy, settings applied at a lower level can override some higher-level settings. - - -### service contract -A set of PHP interfaces that are defined for a module. -A service contract includes data interfaces, which preserve data integrity, and service interfaces, which hide business logic details from service requestors such as controllers, web services, and other modules. -Web APIs can be bound to service contracts via configuration files. - - -### settlement -Settlement occurs when the acquiring bank and the issuer exchange funds and the proceeds are deposited into the merchant account. - - -### Shared Catalog -A feature that allows merchants to create a catalog that can serve as their entire catalog or a subset of it, and then assign custom prices for one or more products. -Merchants can then assign this catalog to one or more companies. -For example, a B2B merchant has three customers who have negotiated specific rates for the merchant’s electronics distribution site. -Using the shared catalog feature, the merchant has: - - -### shipment -A shipment contains products to be delivered and generates a record of the products in an order that have been shipped. -More than one shipment can be associated with a single order. - - -### shipment document -A document that accompanies a shipment. The document lists the products and their quantities in the delivery package. - - -### shipping carrier -A company that transports packages. Common carriers include UPS, FedEx, DHL, and USPS. - - -### shopping cart -The set of products that a customer has selected to purchase, but has not yet purchased. -Also refers to an area of an ecommerce site where these products can be found to review and checkout. - - -### simple product -The most basic product type, a physical item with a single SKU. -Simple products have various pricing and input controls which makes it possible to sell variations of the product. -Simple products can be used in association with grouped, bundle, and configurable products. -A simple product with custom options is sometimes referred to as a composite product. - - -### SKU -Abbreviation for Stock Keeping Unit. -A number or code assigned to a product to identify the product, options, price, and manufacturer. - - -### splash page -A promotional page with a product or advertisement; normally displayed before the home page. - - -### static block -A modular unit of content that can be placed by a user in the CMS on a page to display text and images, or execute snippets of code. -Static blocks contain editable content and can act as landing pages for product categories. -Widgets can be added to static blocks to provide additional functionality. - - -### static content -User-generated content (not generated by code) that does not change frequently. - - -### static files -The collection of assets, such as CSS, fonts, images, and JavaScript that is used by a theme. - - -### store -The Commerce scope level of “store” is the second level of your website’s hierarchy, which goes as follows: website > store > store view. -Stores can be organized into one or many. Each store, potentially, has its own root category, and all share catalog and customer data. -Each store can have multiple store views, which are typically used to present the storefront in a different locale and language. - - - - -### store view -The Commerce scope level of “store view” refers to the third level in the hierarchy of websites, stores and store views. -Store views typically present the storefront in a different locale and language. -To change store views, use the store chooser in the header. - - -### storefront -The online store that customers experience when they visit your Commerce site. - - -## T - -### tax rule -A combination of a product tax class, customer tax class, and tax rate. This rule defines which tax calculation is applied. - - -### template -Short for HTML template or PHTML template. -A PHTML file contains a mixture of HTML markup and PHP code to inject dynamic content into the HTML. -Most blocks have at least one PHTML (template) file that contains the static HTML generated by the block. -In the Admin, email and newsletter templates combine text, images, and variables with HTML markup to produce personalized content that is sent by the system. - - -### theme -Contains graphics and appearance information. -Customizes the look and feel of the store. -Mage-OS can ship themes in (Composer) packages. -But themes can be placed under app / design, which is not shipped in a package. -Packages are the unit of download for Composer, and — via Commerce Marketplace — Commerce users can download CE or EE as a series of packages, where packages contain modules, themes, or language packs. - - -## U - -### UI component -A tag designed for Mage-OS software to enable simpler and more flexible user interface (UI) rendering. -The goals of the UI component system include the following: - - Simplifying Layout Handle XML file - - Moving Admin user interface elements from HTML+JavaScript to a “pure JavaScript” custom widget system - - Enabling the creation of more complex UI components out of smaller component - - Pre-rendering data for UI components as JSON, binding closely to backend data object - - Using AJAX to update component data - - Introducing a new DSL for creating the above item - - -### UPWARD -UPWARD in development. -UPWARD is an acronym for Unified Progressive Web App Response Definition. -An UPWARD definition file describes how a web server delivers and supports a Progressive Web Application. -UPWARD definition files provide details about server behavior using platform-independent, declarative language. -This allows a Progressive Web Application to run on top of an UPWARD-compliant server in any language on any tech stack because the application is only concerned about the HTTP endpoint behavior from the UPWARD server. -An UPWARD server uses a definition file to determine the appropriate process or service for a request from an application shell. -It describes how the server should handle a request and build the response for it. -A PWA project can include an UPWARD definition file to specify its service dependencies. - - -## V - -### Vendor Bundled Extension -Vendor-produced code that extends or customizes Commerce behavior and operates as a third-party extension is considered a Vendor Bundled Extension (VBE). -VBEs are thoroughly tested and included with each supported version of Mage-OS Open Source and Mage-OS. -A VBE can include modules, themes, and language packs. - - -### vertical scaling -Vertical scaling (scaling up) refers to increasing the processing power of a single server or cluster by adding disk or network I/O, CPUs, or RAM. - - -### virtual product -Represents a non-physical product that can be sold, such as a membership, service, warranty, or subscription. -Virtual products can be sold individually, or included as part of the following product types: grouped product and bundle product. -Does not require shipping or inventory. -The process of creating a virtual product and a simple product is nearly the same. -However, because a virtual product is not shipped, there is no Weight field or option to include a gift card. - - -### virtual type -Virtual types are a way to inject different dependencies into existing PHP classes without affecting other classes and without having to create a class file. -Virtual types can only be referenced by argument overrides in a element within di.xml files, never in source code. -They can’t be extended and they can’t be references as dependencies in a classes constructor. - - -## W - -### website -In the Mage-OS software, the highest level of a website hierarchy, above store and store view. -You can have multiple websites, and each website can have a different domain name. -Websites can be set up to share customer data, or to not share data. - - -### widget -A widget is a prepared snippet of code that can be used to place blocks, links, and dynamic content at specific locations on store pages. -You can use widgets to create landing pages for marketing campaigns, display promotional content at specific locations throughout the store. -Widgets can also be used to add interactive elements and action blocks for external review systems, video chats, voting, and subscription forms, or to provide navigation elements for tag clouds and image sliders. \ No newline at end of file +# Glossary of Terms + +[TOC] + +This glossary contains explanations of commonly used terms in the context of programming, PHP, and Magento 2. + +## 1. PHP + +### 1.1 Variable + +A variable in PHP is a named container that can hold a value. It is used to store and manipulate data during the +execution of a program. Variables are declared using the `$` symbol followed by the variable name and an optional +initial value. + +Example: + +```php +$name = "John"; +$age = 25; +``` + +### 1.2 Function + +A function in PHP is a block of reusable code that performs a specific task. It encapsulates a series of statements and +can be called multiple times from different parts of a program. Functions can accept parameters and return values. + +Example: + +```php +function calculateSum($a, $b) { + return $a + $b; +} +``` + +### 1.3 Array + +An array in PHP is a data structure that can store multiple values under a single variable name. It allows you to group +related data together. PHP supports both indexed and associative arrays. Indexed arrays store values with numeric keys, +while associative arrays use string keys. + +Example: + +```php +$fruits = ["apple", "banana", "orange"]; +$person = ["name" => "John", "age" => 25]; +``` + +### 1.4 Class + +A class in PHP is a blueprint for creating objects. It defines the properties (variables) and methods (functions) that +an object of that class can have. Objects are instances of classes and can be created using the `new` keyword. + +Example: + +```php +class Car { + public $brand; + public function startEngine() { + echo "Engine started!"; + } +} + +$myCar = new Car(); +$myCar->brand = "Toyota"; +$myCar->startEngine(); +``` + +## 2. Magento 2 + +### 2.1 Module + +A module in Magento 2 is a self-contained unit that adds specific functionality to the Magento system. It consists of +code, configuration files, templates, and other resources. Modules can be developed by Magento or third-party developers +to extend or modify the behavior of the platform. + +Example: + +``` +app/code/Vendor/Module +``` + +### 2.2 Block + +A block in Magento 2 is a PHP class responsible for generating and managing the presentation logic of a specific part of +a web page. It is typically used to retrieve and process data from models and provide it to templates for rendering. +Blocks are organized in a hierarchical structure and can have child blocks. + +Example: + +```php +class MyBlock extends \Magento\Framework\View\Element\Template +{ + public function getHelloMessage() + { + return "Hello, Magento!"; + } +} +``` + +### 2.3 Layout + +A layout in Magento 2 is an XML file that defines the structure and appearance of a web page. It specifies the blocks, +containers, and their positions within the page. Layout files are used to control the overall layout of a Magento store +and determine which blocks to display on different pages. + +Example: + +```xml + + + + + + + + +``` + +### 2.4 Plugin + +A plugin in Magento 2 is a class that intercepts and modifies the behavior of a public method of another class (the +target class). It allows you to add custom logic before, after, or around the execution of the target method. Plugins +are used for extending or customizing the functionality of Magento without modifying the original code. + +Example: + +```php +class MyPlugin +{ + public function beforeGetName(\Magento\Catalog\Model\Product $product) + { + return ['My custom name']; + } +} +``` + +These are just a few of the many terms and concepts used in programming, PHP, and Magento 2. By understanding and +familiarizing yourself with these terms, you'll be better equipped to work with and understand the code and +documentation within the PHP and Magento 2 ecosystems. diff --git a/graphql-apis.md b/graphql-apis.md index e69de29..b20c13a 100644 --- a/graphql-apis.md +++ b/graphql-apis.md @@ -0,0 +1,186 @@ +# GraphQL API Documentation + +[TOC] + +This document provides comprehensive documentation for the GraphQL APIs in Magento 2. It covers all the necessary +information to understand and utilize the APIs effectively. + +## Introduction + +GraphQL is a query language for APIs that provides a flexible and efficient alternative to traditional RESTful APIs. +Magento 2 provides a comprehensive GraphQL API that allows you to retrieve and manipulate data from the system. This +documentation will guide you through the process of utilizing the GraphQL APIs in Magento 2. + +## Getting Started + +To get started with the Magento 2 GraphQL API, you need to have a basic understanding of GraphQL and familiarity with +PHP and Magento 2. You'll also need to have a valid authentication token to access the API. + +To authenticate and obtain an access token, you can use the Magento 2 token-based authentication system. Once you have +the token, you can include it in the headers of your GraphQL requests as follows: + +``` +Authorization: Bearer +``` + +With the authentication in place, you can start using the GraphQL API to query and mutate data. + +## Querying Data + +To query data using the GraphQL API, you need to specify the fields you want to retrieve in your query. Here's an +example query to get a list of products: + +```graphql +query { + products { + items { + id + name + price { + regularPrice { + amount { + value + currency + } + } + } + } + } +} +``` + +In the above example, we are querying for a list of products and specifying the fields we want to +retrieve (`id`, `name`, `price`). Each field can have sub-fields, allowing you to traverse complex data structures. + +## Mutating Data + +In addition to querying data, you can also use the GraphQL API to mutate (create, update, or delete) data. Here's an +example mutation to create a new customer: + +```graphql +mutation { + createCustomer(input: { + firstname: "John", + lastname: "Doe", + email: "john.doe@example.com", + password: "password123" + }) { + customer { + id + } + } +} +``` + +In the above example, we are using the `createCustomer` mutation to create a new customer. We provide the necessary +input fields (`firstname`, `lastname`, `email`, `password`) to create the customer. The response will include the newly +created customer's `id`. + +## Paginating Results + +When dealing with large result sets, it's important to paginate the results to improve performance. The GraphQL API +provides pagination capabilities using the `pageSize` and `currentPage` parameters. Here's an example of paginating +products: + +```graphql +query { + products( + pageSize: 10, + currentPage: 1 + ) { + items { + id + name + } + total_count + } +} +``` + +In the above example, we are querying for products and specifying the `pageSize` and `currentPage` parameters. These +parameters allow you to control the number of items per page and which page to retrieve. + +## Filtering and Sorting + +The GraphQL API allows you to filter and sort data based on specific criteria. You can use the `filter` parameter to +specify the filtering conditions and the `sort` parameter to define the sorting order. Here's an example of filtering +and sorting products: + +```graphql +query { + products( + filter: { + sku: { + eq: "ABC123" + } + }, + sort: { + name: ASC + } + ) { + items { + id + name + } + } +} +``` + +In the above example, we are filtering products by the `sku` field and sorting them by the `name` field in ascending +order (`ASC`). + +## Error Handling + +When making GraphQL requests, it's important to handle errors properly. The GraphQL API returns detailed error messages +in case of any errors. Here's an example of an error response: + +```json +{ + "errors": [ + { + "message": "The requested SKU is not available.", + "category": "graphql-authorization" + } + ] +} +``` + +In the above example, the error message indicates that the requested SKU is not available. The `category` field provides +additional information about the type of error. + +## Authentication and Authorization + +The Magento 2 GraphQL API supports authentication and authorization using access tokens. You can generate an access +token using the Magento 2 token-based authentication system. The access token should be included in the `Authorization` +header of your GraphQL requests. + +To control access to specific resources, you can configure the GraphQL permissions in the Magento 2 admin panel. This +allows you to define which operations are allowed for different user roles. + +## Caching + +The GraphQL API in Magento 2 supports caching to improve performance. By default, GraphQL responses are cached based on +the query parameters and the user context. You can configure caching options in the Magento 2 admin panel. + +## GraphQL Schema + +The GraphQL API in Magento 2 follows a schema-driven approach. The schema defines the available types, queries, +mutations, and their respective fields. You can explore the GraphQL schema using tools like GraphiQL or GraphQL +Playground. + +To retrieve the GraphQL schema, you can send a request to the following endpoint: + +``` +https://yourmagentoinstallation.com/graphql/schema?query={__schema{types{name}}} +``` + +In the above example, replace `yourmagentoinstallation.com` with your actual Magento 2 installation URL. + +## Conclusion + +This documentation provides a comprehensive guide to the GraphQL APIs in Magento 2. It covers the basics of querying and +mutating data, pagination, filtering and sorting, error handling, authentication and authorization, caching, and +exploring the GraphQL schema. + +By utilizing the power of GraphQL, you can efficiently retrieve and manipulate data from your Magento 2 system, +providing a seamless and flexible experience for your users. diff --git a/how-to-contribute-to-the-magento-2-community.md b/how-to-contribute-to-the-magento-2-community.md index 82884e4..efa16e8 100644 --- a/how-to-contribute-to-the-magento-2-community.md +++ b/how-to-contribute-to-the-magento-2-community.md @@ -1,156 +1,122 @@ - -# Contributor & Reviewer Guide - -- [Code contributions](#code-contributions) -- [Code reviews](#code-reviews) -- [Issues](#issues) - -Mage-OS guidelines for code contributors and reviewers. - -## Code contributions -Mage-OS operates an open contributor model: anyone is welcome and needed to contribute to development, review, and testing. - -Though, some hierarchy is needed to guarantee that the process runs smoothly. Thus, there are some people with higher privileges for merging pull requests. We call them Mage-OS maintainers. - -Everyone can become a Mage-OS maintainer based on the trust earned from the community over time. - -### Contribute to Mage-OS source code -We adopt a [fork and pull model](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/getting-started/about-collaborative-development-models#fork-and-pull-model) to contribute to the Mage-OS codebase. This method allows a contributor to maintain a copy of the forked codebase and quickly sync it with the base copy. - -To merge a set of changes from the fork into the main repository, the contributor submits a pull request from the owned fork to the base repository. - -The kind of expected contributions: -new features in the form of new extensions, hereinafter Mage-OS features -changes to fix and improve Mage-OS features -changes to fix and improve tests -new tooling -changes to fix and improve existing tooling -documentation - -Reviewers will review the submitted pull requests by interacting with contributors through the GitHub platform. In case the contributor is not able to provide needed feedback, the reviewers are free to decide whether to close the pull request or ask other contributors to carry it out. - -We recommend new contributors familiarize themselves with the codebase by choosing issues labeled “good first issue”. - -If a contributor decides to start from an issue, we recommend leaving a comment on it to declare that there is a plan to work on that. This way, other contributors can know that someone will address that issue and, in case, decide to join forces and give assistance. - -Even if most communication about Mage-OS happens on [Discord](http://chat.mage-os.org/), we encourage contributors to start discussions about specific issues and pull requests on GitHub. - -### Code contribution checklist -When submitting a piece of code through a pull request, please follow these recommendations: - -- A pull request should have a meaningful title and description. If the PR is a bug fix, it should include a step-by-step guide to reproduce the bug(s). Any additional reasoning (the whys) that justifies the pull request is more than welcome. The more detailed the information is, the more quickly the PR will be processed and the quicker the review process can be completed. Please take the same care writing the PR description as writing the code changes. - -- A PR not intended to be merged yet must have either a “[WIP]” prefix in the title or the “wip” label. - -- The code should align with the adopted coding standard. At the moment, we can refer to [Adobe Commerce coding stardards](https://developer.adobe.com/commerce/php/coding-standards/). In the future, we would like to automate the process as much as possible with defined rules for static code/architecture analyzers. - -- The commit messages should adhere to the [conventional commit standard](https://www.conventionalcommits.org/en/v1.0.0/). - -- The commit history should be kept clean, which means the less relevant commits of the same pull request are [squashed](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/managing-commits/squashing-commits). - -- If sufficient tests cover the code, it will significantly speed up the review process. In case of a bug fix, the test should fail because of the defect without the changes introduced by the PR, and the changes make the test pass. - -- The PR must not cause other tests to fail. If the failure is because of intended behavioral changes, those tests need to be updated in the same PR, too. - -After a PR is submitted, please feel free to add additional review comments to your PR to explain the change to reviewers. Again, this can speed up the review process. - -After a PR is submitted, chances are that the review process will require some time; please be patient. The amount of time depends on many factors, but if a contributor feels that the PR is waiting for too long, we recommend trying to contact some maintainers on Discord and point out the situation. To find out a frequent reviewer, just look at other merged PRs. - -Be polite and positive in your communication with reviewers. The tone of language can make a big difference. - -While waiting for your PR to be reviewed, a contributor may review others’ PRs if they have time, thus freeing the backlog of pending reviews for the maintainers and accelerating the review of their PR. - -### Contributor assistant (bot) ->✋ This section describes a feature that's still under discussion and still needs to be developed. - -The contributor assistant is a bot that helps automate pull request workflows by using commands entered in comments. - -#### Launch new instances - -``` -// Deploy instance based on PR changes -@mageos give me test instance - - -// Deploy vanilla Magento instance based on the specified branch -@mageos give me 2.4-develop instance - - -// Specific PHP and DB versions -@mageos give me new instance with edition b2b with env php 7.3 database 5.7 -``` - -#### Run tests - -``` -// Run or re-run all required tests against the PR changes -@mageos run all tests - -// Run or re-run specific comma-separated test build(s) -// -// Allowed build names are: -// - Database Compare -// - Functional Tests CE -// - Integration Tests -// - Magento Health Index -// - Sample Data Tests CE -// - Static Tests -// - Unit Tests -// - WebAPI Tests -// -// Please run only needed test builds instead of all when developing. -// Please run all test builds before sending your PR for review. - -// This functionality is limited to Mage-OS maintainers. -@mageos run -``` - -## Code reviews -Every Mage-OS repository contains a `CODEOWNERS` file in the root directory. -The file lists the teams whose members can approve PRs so they may be merged. -At least two reviews by code owners are required before a PR can be merged. - -Everybody else may also review PRs, but they can’t fulfill the merge requirements. -Such additional reviews by others are welcome, as they ease the review process for the code owners, and more eyes spot more bugs. - -> ✋ Currently, code owner team membership is granted by the Mage-OS board of directors and the technical team lead based on merit. In the future, we will probably formalize a technical steering committee for this task. - -When reviewing a pull request, please follow the following guideline: - -- Be polite and positive towards the author of the PR in review comments. The tone of language can make a big difference. - -- Ensure the PR has a meaningful description. If the PR is a bug fix, the description has to include instructions to reproduce the bug manually. If the PR fixes an issue, ensure the issue is linked to the PR. If the description is lacking, please ask the PR author for clarification. It is okay to ask the author for clarification on a side channel (e.g. Discord) and then add the clarification yourself as a comment to the PR. Or, if you have edit privileges, feel free to improve the description by editing it. - -- Once the PR description is sufficient, spend enough time reading the code changes to understand them. This might require reading functionally adjacent code to understand the full context. If the code changes are too hard to understand, please ask the original author to explain or, even better, maybe suggest changes that could make the code more digestible for humans. Generally, the more specific such suggestions are, the better; including examples is good, too. - -- Ensure the code doesn’t introduce any backward incompatible changes unless they were previously agreed to by the technical team lead. If so, ask the technical team leads to state their approval in a comment to the PR. - -- If the PR is a bug fix, reproduce the bug manually. Then apply the PR changes and confirm the behavior is fixed. If the PR adds a new feature, manually test it works as expected. - -- Ensure sufficient tests cover the code and the test suites pass. In case of a bug fix, the tests should fail because of the defect before the changes introduced by the PR, and the changes make the tests pass. If test coverage is not sufficient, either ask the original author to cover the change with tests or - if you have time - offer to write some yourself. Be aware not everyone is familiar with writing tests, which is okay. If necessary, help the PR author with testing, or point them to a resource explaining it. - -- Once the PR is functionally complete, check the code aligns with the adopted coding standard. This should be mostly taken care of by the automated GitHub actions. When suggesting changes to the coding style, be aware that these changes are not really important. If you have the time, maybe offer the original author to make those changes for them. - -- When the PR is functionally complete and coding standard compliant, check the commit messages and history align with the adopted standard. Fixing the commit history requires re-writing the history, which not everybody is familiar with. Be prepared to help the author by explaining the steps to them or by pointing them to a resource explaining the process. - -## Issues -The best way to keep track of bugs is by opening an issue. When creating an issue, please check the following: - -- there isn’t another issue addressing the same problem - -- the issue can be reproduced, preferably on a fresh install with sample data (ideally on an instance provisioned by the GitHub bot once it is available) - -- the issue describes: - - - preconditions and environment - - steps to reproduce - - expected result - - actual result - - any additional information - -Please take the time to provide as much information as possible to help developers understand and reproduce the problem. - -Creating an issue does not automatically mean someone will work on it. -The best way an issue is resolved is to create a PR, raise the topic in Discord or the tech meeting, or lobby for support that someone else picks up the issue and fixes it. - -The issue on GitHub serves to document the learnings and decisions made along the way and to document progress. +# Contributing to the Magento 2 Community + +[TOC] + +## Introduction + +Thank you for your interest in contributing to the vibrant Magento 2 community! Your contributions can help improve the +platform, fix bugs, develop new features, and enhance the overall user experience. This guide will walk you through the +process of contributing to the Magento 2 community, covering everything from setting up your local development +environment to submitting your contributions for review. + +## Prerequisites + +Before you start contributing to the Magento 2 community, ensure that you have the following prerequisites in place: + +1. **Magento 2 instance**: Set up a local development environment with a Magento 2 instance, preferably the latest + stable version. +2. **Git**: Install Git on your machine to help manage your code changes. +3. **GitHub Account**: Create an account on GitHub if you don't already have one. This will enable you to contribute to + the Magento 2 repository. + +## Clone the Magento 2 Repository + +To contribute to the Magento 2 community, you will need to clone the official Magento 2 repository onto your local +machine. Follow these steps to get started: + +1. Open your command line interface and navigate to the directory where you want to clone the Magento 2 repository. +2. Run the following command to clone the repository: + +```shell +git clone https://github.com/magento/magento2.git +``` + +3. Once the cloning process completes, navigate into the `magento2` directory using the following command: + +```shell +cd magento2 +``` + +## Creating a Branch + +Before you start making changes to the Magento 2 codebase, it's important to create a new branch for your contributions. +This ensures that your changes are isolated and can be easily managed. Follow these steps to create a new branch: + +1. Ensure that you are in the `magento2` directory. +2. Run the following command to create a new branch: + +```shell +git checkout -b my-branch-name +``` + +Replace `my-branch-name` with a descriptive name for your branch. For example, if you are fixing a bug related to +customer registration, you could use `fix-customer-registration-bug`. + +## Making Code Changes + +Once you have created a new branch, you can start making code changes to address the issues you want to contribute. Here +are a few examples: + +### Example 1: Fixing a bug + +If you want to fix a bug, follow these steps: + +1. Identify the bug you want to fix. +2. Navigate to the relevant file(s) in the Magento 2 codebase. +3. Make the necessary changes to address the bug. +4. Test your changes to ensure they fix the bug and do not introduce any regressions. + +### Example 2: Developing a new feature + +If you want to develop a new feature, follow these steps: + +1. Identify the feature you want to develop. +2. Plan your implementation and consider the impact on other parts of the codebase. +3. Create new files or modify existing ones to implement the feature. +4. Test your implementation to ensure it works as expected and does not break any existing functionality. + +## Running Tests + +Before submitting your code changes for review, it is essential to run the tests provided by Magento 2 to ensure that +your changes do not introduce any regressions. Follow these steps to run the tests: + +1. Ensure that you are in the `magento2` directory. +2. Run the following command to install the necessary testing dependencies: + +```shell +composer install +``` + +3. Once the installation completes, run the tests using the following command: + +```shell +vendor/bin/phpunit -c dev/tests/unit/phpunit.xml.dist +``` + +Make sure all tests pass successfully before proceeding. + +## Submitting Your Contributions for Review + +Once you have made your code changes and ensured that all tests pass, it's time to submit your contributions for review. +Follow these steps to create a pull request (PR) on GitHub: + +1. Push your branch to the remote repository using the following command: + +```shell +git push origin my-branch-name +``` + +2. Visit the official Magento 2 repository on + GitHub: [https://github.com/magento/magento2](https://github.com/magento/magento2). +3. Click on the "Pull requests" tab. +4. Click on the "New pull request" button. +5. Select your branch from the dropdown menu. +6. Add a descriptive title and provide a clear description of your changes. +7. Click on the "Create pull request" button to submit your contributions for review. + +## Conclusion + +Contributing to the Magento 2 community is an excellent way to improve the platform and collaborate with other +developers. By following the steps outlined in this guide, you can start making a positive impact on the Magento 2 +ecosystem. Remember to always adhere to best practices, thoroughly test your changes, and actively engage with the +community for feedback and guidance. Happy contributing! diff --git a/how-to-get-help-and-support.md b/how-to-get-help-and-support.md index e69de29..ab32392 100644 --- a/how-to-get-help-and-support.md +++ b/how-to-get-help-and-support.md @@ -0,0 +1,110 @@ +# Help and Support + +[TOC] + +## Overview + +Welcome to the Help and Support section of the documentation. Here, we will outline the various avenues available to +obtain assistance for programming queries, troubleshooting issues, and seeking guidance related to PHP and Magento 2 +development. We understand that every developer encounters roadblocks during the development process, and we are +committed to providing the necessary support to ensure smooth progress. + +## Online Resources + +The internet is a vast repository of knowledge and solutions, and there are several online resources where you can find +answers to your questions and obtain support. Here are some popular platforms that can be invaluable in your search for +help: + +### Stack Overflow + +Stack Overflow is a widely-used platform where developers can ask questions and receive answers from the community. It +is home to a large number of experienced developers who are eager to help. You can search for questions and answers +related to your query, and if you can't find what you're looking for, you can ask a new question. + +For example, if you encounter an error while using a Magento 2 API, you can search for related questions by using +relevant keywords such as "Magento 2 API error" or "Magento 2 API not working." If you can't find a suitable answer, you +can post a new question with specific details about the issue, including any error messages you have encountered and the +code you are using. + +### Magento Stack Exchange + +Magento Stack Exchange is a dedicated platform for Magento-related questions. It follows a similar format to Stack +Overflow but focuses specifically on Magento development. Many experienced Magento developers actively participate in +this community, and you can find answers to a wide range of Magento-specific questions. + +For instance, if you need assistance with creating a custom module in Magento 2, you can search for questions related +to "Magento 2 custom module development." If you have a unique question that hasn't been addressed before, you can ask a +new question and specify your requirements and any issues you are facing. + +## Community Forums + +Community forums are another excellent resource for obtaining support and engaging with fellow developers. These forums +allow you to discuss your concerns and seek guidance from experienced members of the PHP and Magento 2 communities. Here +are a couple of prominent community forums worth exploring: + +### Magento Community Forums + +The Magento Community Forums are an official platform for Magento discussions. It provides a space for developers, +merchants, and enthusiasts to collaborate and exchange ideas. You can create an account, participate in conversations, +and ask questions related to Magento development. + +### PHP Developer Forums + +PHP Developer Forums is a community-driven platform for discussions related to PHP development. It covers a broad range +of topics, including PHP frameworks like Magento 2. You can join discussions, seek guidance, and share your expertise +with other PHP developers. + +## Bug Reporting + +If you encounter a bug or believe you have found an issue with PHP or Magento 2, it is important to report it to the +appropriate channels. Reporting bugs helps the development community identify and resolve issues more effectively. Here +is how you can report bugs for PHP and Magento 2: + +### PHP Bug Reporting + +To report a bug in PHP, you can visit the [PHP Bug Tracking System](https://bugs.php.net/) and create a new bug report. +Provide as much information as possible, including a concise description of the bug, steps to reproduce it, and any +relevant code snippets. + +### Magento 2 Bug Reporting + +For Magento 2, you can report bugs on the +official [Magento GitHub repository](https://github.com/magento/magento2/issues). Before reporting a bug, ensure that it +hasn't been reported already by searching the existing issues. If necessary, create a new issue and provide detailed +steps to reproduce the bug, along with any relevant code or error messages. + +## Official Documentation + +Official documentation is an invaluable resource for understanding the intricacies of PHP and Magento 2 development. It +provides detailed explanations, examples, and best practices to help you navigate through various concepts. The official +documentation for PHP can be found at [php.net](https://www.php.net/manual/en/index.php), and for Magento 2, +the [Magento Developer Documentation](https://devdocs.mage-os.org/) is the go-to resource. + +For example, if you need to understand how to use a specific PHP function or explore the available Magento 2 APIs, you +can refer to the relevant sections in the official documentation. The documentation often includes code snippets to +illustrate the usage of various functions and APIs, making it easier to comprehend and apply the concepts. + +## Professional Support + +If you require dedicated support or need assistance beyond what the community or online resources can provide, +professional support options are available. Professional support ensures that your queries receive prompt attention from +trained experts who specialize in PHP and Magento 2 development. + +### Magento Support + +For Magento-specific support, you can explore the +various [Magento Support Plans](https://magento.com/support#support-plans) offered by Adobe. These plans provide access +to a dedicated support team that can assist you with issues, provide guidance, and offer tailored solutions. + +### PHP Consulting Services + +If you need professional support for PHP development, you can consider engaging with consulting firms specializing in +PHP. These firms offer services such as code reviews, performance optimization, and troubleshooting, providing you with +personalized assistance to meet your specific requirements. + +## Conclusion + +Obtaining help and support for PHP and Magento 2 development is essential to navigate challenges and make progress. This +documentation has outlined various resources, including online platforms, community forums, bug reporting procedures, +official documentation, and professional support options. By utilizing these resources effectively, you can overcome +obstacles, enhance your skills, and build robust PHP and Magento 2 applications. diff --git a/how-to-use-and-extend-apis.md b/how-to-use-and-extend-apis.md index e69de29..6a30629 100644 --- a/how-to-use-and-extend-apis.md +++ b/how-to-use-and-extend-apis.md @@ -0,0 +1,292 @@ +# API Documentation: How to Use and Extend APIs in Magento 2 + +[TOC] + +## Introduction + +This documentation aims to provide you with a comprehensive guide on how to use and extend APIs in Magento 2. APIs ( +Application Programming Interfaces) are fundamental tools for integrating and extending the functionality of Magento 2. +This document assumes a basic understanding of programming concepts and familiarity with PHP and Magento 2. + +## API Basics + +APIs in Magento 2 are built using a REST (Representational State Transfer) architecture. RESTful APIs allow you to +interact with Magento 2 resources, such as products, customers, orders, and more, by sending HTTP requests to specific +endpoints. + +Magento 2 provides a set of pre-defined APIs that allow developers to perform various operations on the system. These +operations include reading, creating, updating, and deleting resources. However, you can also extend and customize these +APIs to suit your specific business needs. + +## Using APIs in Magento 2 + +### Authentication + +Before accessing the APIs, you need to authenticate your requests. Magento 2 supports both token-based and OAuth-based +authentication methods. + +For token-based authentication, you need to generate a token for each user who wants to access the APIs. Tokens can be +generated through the Magento admin panel or programmatically via the API. Once you have a valid token, you can include +it in your requests using the `Authorization` header. + +Here's an example using cURL: + +```shell +curl -X GET -H "Authorization: Bearer YOUR_TOKEN" https://example.com/rest/V1/products +``` + +### Request Methods + +Magento 2 APIs support the standard HTTP request methods: GET, POST, PUT, and DELETE. These methods correspond to +different operations: + +- GET: Retrieve resources or collections. +- POST: Create new resources. +- PUT: Update existing resources. +- DELETE: Delete resources. + +The choice of request method depends on the type of operation you want to perform. For example, if you want to retrieve +a list of products, you would use a GET request. If you want to create a new product, you would use a POST request. + +### Data Formats + +Magento 2 APIs support various data formats for both request payloads and responses. The most commonly used formats are +JSON (JavaScript Object Notation) and XML (eXtensible Markup Language). + +By default, Magento 2 APIs return JSON responses. However, you can specify the desired response format by setting +the `Accept` header in your requests. For example, to request XML responses, you can include the following header: + +``` +Accept: application/xml +``` + +### API Endpoints + +Magento 2 provides a wide range of pre-defined API endpoints for different resources. These endpoints follow a +consistent pattern: + +``` +https://example.com/rest/V1/{resource}/{id} +``` + +Where: + +- `resource` is the name of the resource you want to interact with (e.g., `products`, `customers`, `orders`). +- `id` is an optional parameter specifying the identifier of a specific resource. If omitted, the endpoint returns a + collection of resources. + +Here are some examples of API endpoints: + +``` +GET https://example.com/rest/V1/products +GET https://example.com/rest/V1/products/10 +POST https://example.com/rest/V1/products +PUT https://example.com/rest/V1/products/10 +DELETE https://example.com/rest/V1/products/10 +``` + +## Extending APIs in Magento 2 + +Magento 2 allows you to extend and customize the existing APIs to meet your specific business requirements. This section +covers three common techniques: creating custom API endpoints, adding custom methods to existing APIs, and modifying +existing API endpoints. + +### Creating Custom API Endpoints + +To create a custom API endpoint, you need to define a new route in a custom module. This route should map to a +controller that handles the API request and performs the desired actions. + +Here's an example of how to create a custom API endpoint for retrieving a list of custom products: + +1. Create a custom module (e.g., `Vendor_CustomApi`). +2. Define a new route in `etc/webapi.xml`: + +```xml + + + + +``` + +3. Create a controller that handles the API request in `Controller/CustomProducts.php`: + +```php +resultJsonFactory = $resultJsonFactory; + } + + public function execute() + { + // Retrieve and return custom products + $products = ... // Your custom logic here + + $result = $this->resultJsonFactory->create(); + return $result->setData($products); + } +} +``` + +Now, you can access your custom API endpoint using the following URL: + +``` +GET https://example.com/rest/V1/custom-products +``` + +### Adding Custom Methods to Existing APIs + +Magento 2 allows you to add custom methods to existing API interfaces without modifying the core code. This technique is +useful when you need to perform additional operations on a resource. + +For example, let's say you want to add a custom method to the `Magento\Catalog\Api\ProductRepositoryInterface` to +retrieve a product by its SKU. + +1. Create a custom module (e.g., `Vendor_CustomApi`). +2. Define a new interface that extends the existing API interface in `Api/ProductRepositoryInterface.php`: + +```php +productRepository = $productRepository; + } + + public function getBySku($sku) + { + // Implement your custom logic here + + return $this->productRepository->get($sku); + } + + // Implement other methods from the original interface +} +``` + +4. Register your custom implementation in `di.xml`: + +```xml + + + + +``` + +Now, you can use the `getBySku` method in addition to the existing methods of the `ProductRepositoryInterface`. + +### Modifying Existing API Endpoints + +You might need to modify the behavior or response format of existing API endpoints provided by Magento 2. To do so, you +can use plugins or preferences to override the default behavior of the core classes. + +For example, let's say you want to modify the response structure of the `/V1/products` endpoint to include additional +data. + +1. Create a custom module (e.g., `Vendor_CustomApi`). +2. Create a plugin that intercepts the response of the `Magento\Catalog\Api\ProductRepositoryInterface::getList` method + in `Plugin/ProductRepositoryPlugin.php`: + +```php +searchResultsFactory = $searchResultsFactory; + } + + public function afterGetList( + ProductRepositoryInterface $subject, + SearchResultsInterface $searchResults + ): SearchResultsInterface { + // Manipulate the search results or add additional data + foreach ($searchResults->getItems() as $product) { + if ($product instanceof ProductInterface) { + // Add additional data to each product + $product->setCustomData(...); + } + } + + return $searchResults; + } +} +``` + +3. Register your plugin in `di.xml`: + +```xml + + + + + + +``` + +Now, whenever the `/V1/products` endpoint is called, your plugin will intercept the response and modify it according to +your custom logic. + +## Conclusion + +APIs are powerful tools for integrating and extending the functionality of Magento 2. This documentation provided an +overview of using and extending APIs, covering topics such as authentication, request methods, data formats, API +endpoints, creating custom endpoints, adding custom methods, and modifying existing endpoints. By leveraging these +techniques, you can build robust and customized integrations with Magento 2. diff --git a/i18n.md b/i18n.md index e69de29..885b597 100644 --- a/i18n.md +++ b/i18n.md @@ -0,0 +1,84 @@ +# i18n Documentation + +[TOC] + +## Introduction + +Internationalization, often abbreviated as i18n, is the process of designing and developing software applications that +can be easily adapted to different languages and cultures. In the context of web development, it refers to the ability +to make a website or web application accessible and adaptable to users from different regions and linguistic +backgrounds. This documentation will provide an overview of i18n concepts and explain how to implement them using PHP +and Magento 2. + +## Localization vs Internationalization + +Before diving into the details of i18n, it is essential to understand the difference between localization and +internationalization. Localization, abbreviated as l10n, refers to the process of adapting software to a specific locale +or language. It involves translating the user interface, content, and other elements to suit the target audience's +preferences. Internationalization, on the other hand, is the process of designing and developing software in a way that +makes it easy to localize. + +## Internationalization in Magento 2 + +Magento 2, a popular e-commerce platform, provides robust support for internationalization. It offers features and +functionalities that allow developers to build multilingual online stores easily. Some of the key elements of +internationalization in Magento 2 include: + +### Translation Files + +Magento 2 employs a translation mechanism that uses CSV files to store translations for different languages. Each CSV +file contains a mapping between the original phrases and their translated counterparts. These files are organized under +the `i18n` directory in a module or theme. + +For example, to translate a phrase in English to Spanish, you need to create a CSV file named `es_ES.csv` (assuming the +target locale is Spanish) and place it in the appropriate module or theme directory. The content of the CSV file would +look like this: + +```csv +"Hello","Hola" +"Welcome","Bienvenido" +``` + +### Translation Functions + +Magento 2 provides translation functions that enable developers to translate text directly within their code. These +functions automatically retrieve the translated version of a phrase based on the current locale. + +The primary translation function in Magento 2 is `__('phrase')`, which is similar to the `gettext` function in PHP. This +function takes a phrase as an argument and returns the translated version of the phrase based on the current locale. For +example: + +```php +echo __("Hello"); // Output depends on the current locale +``` + +### Locale-Specific Formatting + +Different locales have different formatting conventions for numbers, currencies, dates, and times. Magento 2 +incorporates the `Intl` extension to handle locale-specific formatting requirements. The `Intl` extension provides +classes and functions to format numbers, currencies, dates, and times based on the current locale. + +For instance, to format a date in a locale-specific manner, you can use +the `Magento\Framework\Stdlib\DateTime\TimezoneInterface` class. Here's an example: + +```php +/** @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone */ +$timezone->formatDateTime($date, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::SHORT); +``` + +### Locale-Specific Configuration + +Magento 2 allows developers to configure various aspects of their store based on the current locale. For instance, you +can set the default currency for a specific locale, define locale-specific date and time formats, and configure +locale-specific tax rules. + +To configure locale-specific settings in Magento 2, you can navigate to the admin panel, select "Stores" from the main +menu, and then choose "Configuration." From there, you can modify various settings under the "General" and "Currency +Setup" sections. + +## Conclusion + +Internationalization is a crucial aspect of modern web development, especially for applications targeting a global +audience. Magento 2 provides developers with robust tools and features to implement i18n seamlessly. By utilizing +translation files, translation functions, locale-specific formatting, and configuration options, developers can create +multilingual and culturally adaptable online stores. diff --git a/indexer-xml.md b/indexer-xml.md deleted file mode 100644 index e69de29..0000000 diff --git a/indexer_xml.md b/indexer_xml.md new file mode 100644 index 0000000..ec0a960 --- /dev/null +++ b/indexer_xml.md @@ -0,0 +1,107 @@ +# `indexer.xml` Reference Documentation + +[TOC] + +The indexer.xml file is an important configuration file in Magento 2 that defines the behavior of indexers. Indexers are +responsible for updating and retrieving data from the database to improve the performance of query execution. + +## File Location + +The indexer.xml file is located in the `etc` directory of your custom module or theme. The file path is as follows: + +```plaintext +app/code/[Vendor]/[Module]/etc/indexer.xml +``` + +Alternatively, for a theme, the file path is: + +```plaintext +app/design/frontend/[Vendor]/[Theme]/etc/indexer.xml +``` + +## File Structure + +The indexer.xml file follows a specific structure that defines how indexers are configured. It consists of three main +sections: + +1. `` - This is the root element that encloses all the other sections of the indexer.xml file. +2. `` - This section defines the individual indexers and their configuration. +3. `` - This section specifies the sources of data that indexers will use to update or retrieve data from the + database. + +Here is an example of the basic structure of the indexer.xml file: + +```xml + + + + + + + + + +``` + +## Defining Indexers + +To define an indexer, you need to add a `` section within the `` section of the indexer.xml file. +Each `` section should have a unique `id` attribute and a `view_id` attribute that identifies the indexer's +view. + +Here is an example of a custom indexer definition: + +```xml + + + +``` + +## Configuring Indexers + +Within the `` section, you can define various aspects of the indexer's behavior. Some of the key configuration +options include: + +- `` - Specifies the title of the indexer that will be displayed in the Magento admin panel. +- `<description>` - Provides a brief description of the indexer's purpose. +- `<model>` - Specifies the class responsible for performing the indexing operations. +- `<indexer_id>` - Specifies the unique identifier for the indexer. +- `<status>` - Sets the initial status of the indexer (e.g., `Working`, `Scheduled`, `Invalid`, etc.). +- `<depends>` - Specifies any dependencies that the indexer has on other indexers. + +Here is an example of a custom indexer configuration: + +```xml +<indexer id="my_custom_indexer" view_id="my_custom_indexer"> + <title>My Custom Indexer + This indexer updates the custom data in the database. + [Vendor]\[Module]\Model\Indexer\MyCustomIndexer + my_custom_indexer + Working + + [Other_Module]::indexer_id + + +``` + +## Configuring Data Sources + +Data sources are the entities from which the indexers retrieve or update data. Each `` section can have one or +more `` sections to specify the sources of data. + +Here is an example of a data source configuration: + +```xml + + + +``` + +The `[Data_Source_Name]` should match the name specified in the `` section of the indexer.xml file. + +## Conclusion + +The indexer.xml file is an essential configuration file in Magento 2 that defines the behavior of indexers. By +understanding its structure and the available configuration options, you can effectively configure and manage indexers +in your custom modules or themes. diff --git a/indexers.md b/indexers.md index e69de29..359fe91 100644 --- a/indexers.md +++ b/indexers.md @@ -0,0 +1,125 @@ +# Indexers Documentation + +[TOC] + +## Overview + +Indexers are an essential component of Magento 2's architecture for efficient data retrieval. They play a significant +role in improving the performance of your Magento store by pre-calculating and storing data in an optimized format, +allowing for quick and efficient searching and filtering operations. + +This documentation will provide you with a comprehensive understanding of indexers in Magento 2, including their +purpose, types, configuration, and management. + +## What are Indexers? + +In Magento 2, indexers are responsible for transforming raw data from your store's database into a format that is +optimized for fast searching and filtering. They allow for efficient retrieval of data without the need for complex +database queries, significantly improving the performance of read operations. + +Indexers are a crucial part of Magento's architecture as they ensure real-time data accuracy while maintaining high +performance. By updating only the affected portions of the index, Magento minimizes the time and resources required to +keep the index up-to-date. + +## Types of Indexers + +Magento 2 provides several built-in indexers, each designed to handle specific data entities and attributes. Here are +some examples of the most commonly used indexers: + +1. **Product Indexer**: Handles product-related data, such as attributes, categories, prices, and stock status. +2. **Category Indexer**: Manages category-related data, including category hierarchies, URLs, and product assignments. +3. **Customer Indexer**: Maintains customer-related data, such as names, addresses, and account information. +4. **Order Indexer**: Handles order-related data, including order status, customer details, and product information. + +These are just a few examples, and depending on your specific Magento setup and extensions, you may have additional +indexers available. + +## Indexer Configuration + +Magento 2 provides a configuration file (`etc/indexer.xml`) that specifies the indexers and their corresponding index +tables. This file is located in the module's directory, typically in `app/code/[Vendor]/[Module]/etc/indexer.xml`. + +To configure an indexer, you define it in the `indexer.xml` file with its associated data source and index table. Here's +an example of configuring a custom indexer: + +```xml + + + + Custom Indexer + This is a custom indexer for XYZ data. + custom_indexer + + + + +``` + +In this example, we define a custom indexer with the identifier `custom_indexer`. The `class` attribute points to the +indexer's implementation class. The `dataSource` element specifies the class responsible for retrieving the data to be +indexed, while the `indexTable` element defines the name of the index table. + +## Managing Indexers + +Magento 2 provides a range of commands to manage and interact with indexers via the command-line interface (CLI). These +commands allow you to enable/disable, update, and manage the status of individual indexers. + +To view the current status of all indexers, use the following command: + +```bash +bin/magento indexer:status +``` + +To enable or disable a specific indexer, use the following command: + +```bash +bin/magento indexer:set-mode +``` + +For example, to enable the product indexer: + +```bash +bin/magento indexer:set-mode catalog_product_attribute update +``` + +To update/reindex a specific indexer, use the following command: + +```bash +bin/magento indexer:reindex +``` + +For example, to reindex the product indexer: + +```bash +bin/magento indexer:reindex catalog_product_attribute +``` + +Remember to run the necessary indexers after making configuration changes to ensure the data is up-to-date. + +## Indexer Troubleshooting + +If you encounter issues with indexers, there are a few troubleshooting steps you can take: + +1. **Check Indexer Status**: Verify the status of all indexers using the `bin/magento indexer:status` command. Look for + any indexers with a "Working" status or errors, as these could indicate potential issues. +2. **Check Logs**: Examine the Magento logs, especially the `system.log` and `exception.log`, for any relevant error + messages or exceptions related to indexers. +3. **Check Server Resources**: Ensure that your server has sufficient resources (memory, CPU, disk space) to accommodate + the indexing process. Insufficient resources can cause indexing failures or slowdowns. +4. **Reindex Manually**: If the automated reindexing fails, try manually reindexing specific indexers using + the `bin/magento indexer:reindex` command. Monitor the output for any error messages or warnings. +5. **Rebuild Index Tables**: In some cases, rebuilding the index tables can resolve issues. This can be done by + truncating the index table(s) associated with the problematic indexer(s) and then running a full reindex. + +If the above steps do not resolve the issue, consider seeking assistance from the Magento community or support channels +for further troubleshooting and debugging. + +## Conclusion + +Indexers are a vital part of Magento 2's performance optimization strategy, allowing for efficient data retrieval and +search operations. By understanding the different types of indexers, configuring them correctly, and managing them +effectively, you can ensure your Magento store delivers fast and accurate results to your customers. + +For additional information and advanced usage, refer to the official Magento 2 documentation and community resources. +Happy indexing! diff --git a/installation-guide.md b/installation-guide.md index e69de29..05d26ee 100644 --- a/installation-guide.md +++ b/installation-guide.md @@ -0,0 +1,102 @@ +# Installation Guide for Magento 2 + +[TOC] + +## Introduction + +This installation guide provides step-by-step instructions for installing Magento 2 on your server. The guide assumes +you have a basic understanding of programming concepts, specifically PHP and Magento 2. By following these instructions, +you will be able to successfully install Magento 2 and start building your online store. + +## Prerequisites + +Before proceeding with the installation, please ensure that your server meets the following prerequisites: + +- PHP 8.1 or later +- MySQL 8.1 or later +- Apache or Nginx web server +- Composer 2 + +## Step 1: Download Magento 2 + +The first step in the installation process is to download the Magento 2 package. You can download the package from the +official Magento website or use Composer to install it. + +To download Magento 2 using Composer, open your command line interface and navigate to your project directory. Then, run +the following command: + +```bash +composer create-project --repository-url=... . +``` + +This command will download the latest version of Magento 2 and all its dependencies. + +## Step 2: Configure the Database + +Magento 2 requires a database to store its data. Before proceeding with the installation, you need to configure the +database settings. + +Start by creating a new database for your Magento 2 installation. You can use a tool like phpMyAdmin or the command line +to create the database. + +Next, open the `app/etc/env.php` file in your Magento 2 installation directory. Look for the following section: + +```php +'db' => [ + 'table_prefix' => '', + 'connection' => [ + 'default' => [ + 'host' => 'localhost', + 'dbname' => 'magento', + 'username' => 'root', + 'password' => '', + 'active' => '1' + ] + ] +], +``` + +Update the database settings according to your environment. Replace `'localhost'` with the hostname of your database +server, `'magento'` with the name of your database, `'root'` with the username, and `''` with the password. Leave +the `'table_prefix'` field empty unless you want to specify a prefix for your Magento tables. + +## Step 3: Run the Installation Wizard + +Once the database is configured, you can run the Magento 2 installation wizard. Open your web browser and navigate to +the URL where you placed your Magento 2 files. + +You will be greeted with the Magento 2 installation wizard. Follow the on-screen instructions to complete the +installation process. Make sure to provide the necessary information, such as your store name, admin email, username, +and password. + +During the installation, Magento 2 will perform various database operations and install the necessary tables. After the +installation is complete, you will be redirected to the Magento admin panel. + +## Step 4: Enable the Magento 2 Cron Job + +Magento 2 relies on a cron job to perform scheduled tasks, such as indexing, cache flushing, and sending email +notifications. To enable the Magento 2 cron job, you need to add a cron job entry to your server. + +Open your command line interface and run the following command: + +```bash +crontab -e +``` + +This command will open the cron job configuration file. Add the following line to the file: + +```bash +* * * * * /bin/magento cron:run >> /var/log/cron.log +``` + +Replace `` with the path to your PHP binary and `` with the path to your Magento 2 +installation directory. + +Save the file and exit the editor. The cron job will now run every minute and execute the Magento 2 cron tasks. + +## Conclusion + +Congratulations! You have successfully installed Magento 2 on your server. You can now start building your online store +and customizing it to fit your needs. + +Please refer to the official Magento 2 documentation for more information on how to configure and use Magento 2. diff --git a/integration-testing.md b/integration-testing.md index e69de29..37b7aad 100644 --- a/integration-testing.md +++ b/integration-testing.md @@ -0,0 +1,150 @@ +# Integration Testing Documentation + +[TOC] + +## Introduction + +Integration testing is a crucial part of the software development process, particularly in complex systems like Magento +2. It verifies that different components of an application work together as expected when integrated. This documentation +provides an overview of integration testing in Magento 2, including its importance, common techniques, and best +practices. + +## Why Integration Testing? + +Integration testing ensures that individual components, such as modules, classes, or services, can seamlessly interact +with each other without causing unexpected issues. It identifies integration problems early in the development cycle, +preventing them from becoming more difficult and expensive to fix later on. + +## Integration Testing Techniques + +Magento 2 provides several techniques to perform integration testing: + +### Unit Tests + +Unit tests are the foundation of integration testing. They focus on testing individual units of code, such as functions +or methods, in isolation. These tests ensure that each unit behaves as expected when integrated with other units. Unit +testing frameworks like PHPUnit are commonly used in Magento 2 to write unit tests. + +Example unit test using PHPUnit: + +```php +class ExampleTest extends \PHPUnit\Framework\TestCase +{ + public function testAddition() + { + $calculator = new Calculator(); + $result = $calculator->add(2, 3); + + $this->assertEquals(5, $result); + } +} +``` + +### Integration Tests + +Integration tests go beyond unit tests by verifying the interaction of multiple units together. They ensure that +components integrate correctly and work together as intended. Integration tests often cover scenarios where units +communicate with databases, external services, or other modules. + +Example integration test using Magento 2's testing framework: + +```php +class ExampleIntegrationTest extends \Magento\TestFramework\TestCase\AbstractController +{ + public function testCustomerLogin() + { + $this->dispatch('customer/account/login'); + $this->assertRedirectTo('customer/account/index'); + } +} +``` + +### API Testing + +API testing focuses on testing the integration of an application's APIs. It ensures that APIs behave correctly, handle +requests and responses properly, and maintain data integrity. + +Example API test using PHPUnit and Guzzle: + +```php +class ExampleApiTest extends \PHPUnit\Framework\TestCase +{ + public function testGetUser() + { + $client = new \GuzzleHttp\Client(); + + $response = $client->get('https://api.example.com/users/1'); + $data = json_decode($response->getBody(), true); + + $this->assertEquals('John Doe', $data['name']); + } +} +``` + +## Best Practices for Integration Testing in Magento 2 + +### Use Test Fixtures + +Test fixtures are pre-defined data sets that provide a known starting point for integration tests. They ensure +consistent and predictable test environments. In Magento 2, fixtures can be created using +the `Magento\TestFramework\Helper\Bootstrap` class or by extending +the `Magento\TestFramework\TestCase\AbstractController` class. + +Example fixture creation in Magento 2: + +```php +class ExampleIntegrationTest extends \Magento\TestFramework\TestCase\AbstractController +{ + protected function setUp(): void + { + $this->setUpBeforeClass(); + $this->loadFixture('example_fixture'); + } +} +``` + +### Isolate External Dependencies + +When performing integration tests, it's crucial to isolate external dependencies, such as databases, third-party APIs, +or services. This helps maintain test reliability and prevents issues caused by external factors. Techniques like +mocking and stubbing are commonly used to isolate dependencies. + +Example dependency isolation using PHPUnit: + +```php +class ExampleIntegrationTest extends \PHPUnit\Framework\TestCase +{ + public function testOrderTotalCalculation() + { + $order = $this->getMockBuilder(Order::class) + ->disableOriginalConstructor() + ->getMock(); + + $order->method('getTotal')->willReturn(100); + + $calculator = new OrderTotalCalculator(); + $result = $calculator->calculate($order); + + $this->assertEquals(105, $result); + } +} +``` + +### Keep Tests Isolated and Independent + +Each integration test should be independent of others and should not rely on shared state or previous test outcomes. +Isolating tests ensures that failures are easier to diagnose and reproduce. Magento 2's testing framework provides tools +for database rollbacks and fixtures to help maintain test independence. + +### Run Tests Regularly + +To ensure the ongoing stability and reliability of your Magento 2 application, it's essential to run integration tests +regularly, ideally as part of a continuous integration (CI) or continuous delivery (CD) pipeline. Running tests +frequently helps catch integration issues early and enables developers to address them promptly. + +## Conclusion + +Integration testing is a critical aspect of software development, including Magento 2 projects. By performing +integration testing, you can detect and resolve issues in the interactions between different components, ensuring the +overall quality and stability of your application. Following the best practices outlined in this documentation will help +you write effective and reliable integration tests for your Magento 2 projects. diff --git a/javascript-in-magento-2.md b/javascript-in-magento-2.md index e69de29..30758a5 100644 --- a/javascript-in-magento-2.md +++ b/javascript-in-magento-2.md @@ -0,0 +1,192 @@ +# JavaScript in Magento 2 Documentation + +[TOC] + +## Introduction + +Magento 2 is a powerful e-commerce platform that supports the use of JavaScript to enhance the user experience and add +dynamic functionality to your storefront. This documentation provides a comprehensive guide to JavaScript in Magento 2, +covering important concepts, best practices, and examples. + +## JavaScript Libraries in Magento 2 + +Magento 2 leverages several popular JavaScript libraries to facilitate development and provide a robust set of tools and +features. The key libraries used in Magento 2 include: + +- [jQuery](https://jquery.com/): A fast and compact JavaScript library that simplifies HTML document traversing, event + handling, and Ajax interactions. +- [RequireJS](https://requirejs.org/): A JavaScript file and module loader that allows modular development and optimizes + resource loading. +- [KnockoutJS](https://knockoutjs.com/): A JavaScript library that enables the creation of responsive and dynamic user + interfaces with a clean and flexible MVVM architecture. +- [Magento_Ui](https://devdocs.magento.com/guides/v2.4/javascript-dev-guide/javascript/js-coding-standard.html): A + Magento 2-specific JavaScript library that provides reusable UI components and widgets. + +## Using JavaScript in Magento 2 + +Magento 2 offers various ways to include and utilize JavaScript in your modules or themes. Here are a few key methods: + +### Adding JavaScript to Pages + +You can add JavaScript to specific pages by declaring dependencies in the `requirejs-config.js` file of your module or +theme. Here's an example that adds a custom JavaScript file to a specific page: + +```javascript +// app/code/YourVendor/YourModule/view/frontend/requirejs-config.js + +var config = { + map: { + '*': { + 'your-custom-js': 'YourVendor_YourModule/js/your-custom-js', + } + } +}; +``` + +In the above example, 'your-custom-js' is the name of your custom JavaScript file, and ' +YourVendor_YourModule/js/your-custom-js' is the path to the JavaScript file relative to your module or theme. + +### Using UI Components + +Magento 2 provides UI components that encapsulate JavaScript functionality and can be easily integrated into your +modules or themes. You can create custom UI components or extend existing ones to meet your specific requirements. +Here's an example of adding a custom UI component to a template file: + +```html + + +
+ +
+ + +``` + +In this example, 'custom-component.html' is the template file for your custom UI component, and ' +YourVendor_YourModule/js/custom-component' is the JavaScript file that defines the behavior of your UI component. + +## JavaScript Best Practices in Magento 2 + +To ensure efficient and maintainable JavaScript code, it is important to follow best practices when developing in +Magento 2. Here are some key considerations: + +### Use RequireJS for Module Loading + +Magento 2 utilizes RequireJS for module loading. When developing custom JavaScript modules, make sure to define +dependencies properly and use the `define` function to encapsulate module functionality. This ensures proper ordering of +script loading and avoids conflicts. + +### Leverage KnockoutJS for UI Interactions + +KnockoutJS is the recommended library for handling user interactions and updating UI components in Magento 2. Use +KnockoutJS observables and bindings to create responsive and dynamic user interfaces. + +### Minimize DOM Manipulation + +Excessive DOM manipulation can degrade performance. Instead, make use of KnockoutJS bindings and the Magento 2 UI +component system to update UI elements efficiently. + +### Follow Magento 2 JavaScript Coding Standards + +Magento 2 has specific coding standards for JavaScript. Adhering to these standards ensures consistency and readability +across your codebase. Familiarize yourself with the Magento 2 JavaScript coding standards described in the official +documentation. + +## Code Examples + +Let's conclude this documentation with a few code examples that illustrate the concepts discussed above. Refer to these +examples for practical implementation guidance: + +- [Example 1: Adding a Custom JavaScript File to a Page](#example-1-adding-a-custom-javascript-file-to-a-page) +- [Example 2: Creating a Custom UI Component](#example-2-creating-a-custom-ui-component) + +### Example 1: Adding a Custom JavaScript File to a Page + +To add a custom JavaScript file to a specific page, follow these steps: + +1. Create the JavaScript file at the desired location ( + e.g., `app/code/YourVendor/YourModule/view/frontend/web/js/your-custom-js.js`). + +2. Declare the JavaScript file as a dependency in the `requirejs-config.js` file of your module or theme: + +```javascript +// app/code/YourVendor/YourModule/view/frontend/requirejs-config.js + +var config = { + map: { + '*': { + 'your-custom-js': 'YourVendor_YourModule/js/your-custom-js', + } + } +}; +``` + +3. Use the JavaScript file in your page by adding the following code to the corresponding template file: + +```html + + + +``` + +### Example 2: Creating a Custom UI Component + +To create a custom UI component in Magento 2, follow these steps: + +1. Create the UI component template file ( + e.g., `app/code/YourVendor/YourModule/view/frontend/web/template/custom-component.html`) and define the UI component + markup. + +2. Create the JavaScript file that defines the behavior of the UI component ( + e.g., `app/code/YourVendor/YourModule/view/frontend/web/js/custom-component.js`). + +3. In the template file where you want to use the custom UI component, add the following code: + +```html + + +
+ +
+ + +``` + +These code examples should help you understand the practical implementation of JavaScript in Magento 2. + +## Conclusion + +This documentation has provided a comprehensive guide to JavaScript in Magento 2, covering important concepts, best +practices, and practical examples. By leveraging JavaScript libraries, utilizing various methods of including +JavaScript, and following best practices, you can enhance the functionality and user experience of your Magento 2 +storefront. Happy coding! diff --git a/javascript-testing.md b/javascript-testing.md index e69de29..d1d9305 100644 --- a/javascript-testing.md +++ b/javascript-testing.md @@ -0,0 +1,182 @@ +# JavaScript Testing Documentation + +[TOC] + +## Introduction + +JavaScript testing is a crucial process in web development as it allows developers to ensure the reliability and +correctness of their code. In this documentation, we will explore the various aspects of JavaScript testing, including +testing frameworks, tools, and best practices. By following these guidelines, you will be able to write effective tests +for your JavaScript code and improve the overall quality and maintainability of your projects. + +## Testing Frameworks + +Testing frameworks provide a structure and set of tools to write and run tests. They typically include features such as +test runners, assertions, and mocking utilities. Let's take a look at some popular JavaScript testing frameworks: + +### Jest + +Jest is a widely-used testing framework developed by Facebook. It is known for its simplicity, speed, and great +developer experience. Jest provides a powerful set of features, including built-in mocking, code coverage, and snapshot +testing. Here's an example of a simple test case using Jest: + +```javascript +test('adds 1 + 2 to equal 3', () => { + expect(1 + 2).toBe(3); +}); +``` + +### Mocha + +Mocha is a flexible testing framework that allows you to choose your own assertion library and test runner. It provides +a clean and minimalistic API for writing tests. Mocha supports both synchronous and asynchronous testing, making it +suitable for a variety of testing scenarios. Here's an example of a Mocha test: + +```javascript +const assert = require('assert'); + +describe('Array', () => { + describe('#indexOf()', () => { + it('should return -1 when the value is not present', () => { + assert.strictEqual([1, 2, 3].indexOf(4), -1); + }); + }); +}); +``` + +### Jasmine + +Jasmine is a behavior-driven development (BDD) testing framework that provides an expressive syntax for writing tests. +It aims to be easy to read and understand, making it a great choice for teams with non-technical stakeholders. Jasmine +includes built-in support for spies, mocks, and asynchronous testing. Here's an example of a Jasmine test: + +```javascript +describe('Calculator', () => { + let calculator; + + beforeEach(() => { + calculator = new Calculator(); + }); + + it('should add two numbers correctly', () => { + expect(calculator.add(2, 3)).toEqual(5); + }); + + it('should subtract two numbers correctly', () => { + expect(calculator.subtract(5, 2)).toEqual(3); + }); +}); +``` + +## Unit Testing + +Unit testing is a testing methodology where individual units of code, such as functions or classes, are tested in +isolation. The purpose is to verify that each unit behaves as expected and to identify any defects early in the +development process. Let's explore some best practices for unit testing JavaScript code: + +### Isolate Dependencies + +When writing unit tests, it is crucial to isolate dependencies to ensure that each unit is tested in isolation. This can +be achieved by using mocking or stubbing techniques. For example, in a Magento 2 module, if a JavaScript function relies +on an API call, you can use a mocking library like `sinon` to stub the API response and test the function's behavior +independently. + +```javascript +// Example using sinon to stub an API call +const sinon = require('sinon'); +const myModule = require('./myModule'); +const api = require('./api'); + +describe('myModule', () => { + it('should handle API response correctly', () => { + const apiStub = sinon.stub(api, 'get').resolves({data: 'test'}); + + return myModule.doSomething().then(() => { + expect(apiStub.calledOnce).toBe(true); + // assert other expectations + }); + }); +}); +``` + +### Test Coverage + +Achieving high test coverage is essential to ensure that your code is thoroughly tested. Test coverage measures the +percentage of code that is executed during tests. Various tools, such as Istanbul or Jest's built-in coverage report, +can help you analyze your code coverage. Aim to have a high level of coverage for critical and complex code paths. + +### Use Test Doubles + +Test doubles, such as mocks, stubs, and spies, are essential tools for unit testing. They allow you to replace real +dependencies with controlled substitutes, enabling you to test specific scenarios and behaviors. For example, you can +use a spy to verify if a function has been called with specific arguments. + +```javascript +// Example using jasmine's spyOn +const myModule = require('./myModule'); +const dependency = require('./dependency'); + +describe('myModule', () => { + it('should call dependency function correctly', () => { + spyOn(dependency, 'myFunction'); + myModule.doSomething(); + expect(dependency.myFunction).toHaveBeenCalledWith('test'); + }); +}); +``` + +## Integration Testing + +Integration testing focuses on testing the interactions between multiple components or systems. In the context of +JavaScript, integration tests may involve testing the interaction between the frontend JavaScript code and backend APIs, +services, or databases. Here are some considerations for integration testing: + +### Setup and Teardown + +In integration tests, it is crucial to properly set up the test environment before each test and clean up afterward. +This ensures that each test has a consistent starting point and avoids conflicts between tests. For example, when +testing a Magento 2 module that interacts with a database, you should create a test database and populate it with the +necessary data before running the tests. + +### Test Real-world Scenarios + +Integration tests should cover real-world scenarios and edge cases to ensure that your JavaScript code works correctly +in a production-like environment. For example, if your JavaScript code communicates with an API, you should test various +API responses, such as success, failure, and error scenarios. + +### Use Mock APIs + +To avoid dependency on external systems during integration tests, you can use mock APIs or API stubs. This allows you to +simulate API responses without making actual requests to the backend. Tools like `msw` or `nock` can help you mock API +requests and responses easily. + +```javascript +// Example using msw to mock API requests +import {rest} from 'msw'; +import {setupServer} from 'msw/node'; +import myModule from './myModule'; + +const server = setupServer( + rest.get('/api/data', (req, res, ctx) => { + return res(ctx.json({data: 'test'})); + }) +); + +beforeAll(() => server.listen()); +afterEach(() => server.resetHandlers()); +afterAll(() => server.close()); + +describe('myModule', () => { + it('should handle API response correctly', async () => { + const result = await myModule.fetchData(); + expect(result).toEqual({data: 'test'}); + }); +}); +``` + +## Conclusion + +JavaScript testing is an essential part of the development process, allowing you to ensure the correctness and +reliability of your code. By using testing frameworks, following best practices, and writing comprehensive unit and +integration tests, you can improve the quality and maintainability of your JavaScript code. Remember to isolate +dependencies, achieve high test coverage, and use test doubles effectively. Happy testing! diff --git a/knockoutjs-integration.md b/knockoutjs-integration.md index e69de29..45da649 100644 --- a/knockoutjs-integration.md +++ b/knockoutjs-integration.md @@ -0,0 +1,118 @@ +# KnockoutJS Integration Documentation + +[TOC] + +## Introduction + +KnockoutJS is a powerful JavaScript library that allows you to create dynamic and responsive user interfaces. It is +particularly useful for integrating with PHP frameworks like Magento 2, as it provides a seamless way to bind data to +the UI and handle user interactions. This documentation will guide you through the process of integrating KnockoutJS +into your Magento 2 project, explaining the key concepts and providing concrete examples. + +## Prerequisites + +Before diving into KnockoutJS integration, it is important to ensure that you have a basic understanding of PHP, Magento +2, and JavaScript. Familiarity with object-oriented programming and concepts like view models and observables will be +beneficial as well. + +## Getting Started + +To integrate KnockoutJS into your Magento 2 project, follow these steps: + +1. Include KnockoutJS library: Add the KnockoutJS library to your project by including the following line in your + template file or layout XML: + ```html + + ``` + +2. Create a View Model: A view model is a JavaScript object that represents the data and behavior of your UI components. + In Magento 2, you can define a view model in a separate JS file or inline within a script tag. Here's an example of + defining a view model inline: + ```html + + ``` + +3. Bind Data to the UI: To bind data from the view model to the UI, use KnockoutJS data binding syntax. You can use + the `data-bind` attribute on HTML elements to specify the binding. For example: + ```html +
+ ``` + +4. Handle User Interactions: KnockoutJS provides a set of event bindings to handle user interactions. You can use + the `click`, `submit`, `event`, and other bindings to attach event handlers to HTML elements. Here's an example of + handling a click event: + ```html + + ``` + + In your view model, define the corresponding function: + ```javascript + var ViewModel = function() { + // ... + this.handleClick = function() { + // Handle the click event here + }; + }; + ``` + +## Advanced Usage + +KnockoutJS offers many advanced features that can enhance your Magento 2 project's user interface. Here are a few +examples: + +### Computed Observables + +Computed observables are special observables that automatically update whenever their dependencies change. They are +useful when you need to compute a value from other observables. Here's an example of using a computed observable: + +```javascript +var ViewModel = function () { + this.firstName = ko.observable('John'); + this.lastName = ko.observable('Doe'); + + this.fullName = ko.computed(function () { + return this.firstName() + ' ' + this.lastName(); + }, this); +}; +``` + +In the above example, the `fullName` computed observable depends on `firstName` and `lastName`. Whenever either of them +changes, the `fullName` will automatically update. + +### Observables Arrays + +Observables arrays are arrays that automatically track changes to their elements. They are useful when you need to +dynamically add or remove elements from a list. Here's an example of using an observable array: + +```javascript +var ViewModel = function () { + this.items = ko.observableArray(['Apple', 'Banana', 'Orange']); + + this.addItem = function () { + this.items.push('New Item'); + }; + + this.removeItem = function (item) { + this.items.remove(item); + }; +}; +``` + +In the above example, the `items` observable array holds a list of items. The `addItem` function adds a new item to the +array, while the `removeItem` function removes a specific item. + +## Conclusion + +Integrating KnockoutJS into your Magento 2 project allows you to create dynamic and responsive user interfaces easily. +By following the steps outlined in this documentation and exploring the advanced features, you can take full advantage +of KnockoutJS's capabilities. Remember to refer to the official KnockoutJS documentation for more detailed information +on specific features and concepts. + +Happy coding! diff --git a/layout-xml.md b/layout-xml.md deleted file mode 100644 index e69de29..0000000 diff --git a/layout_xml.md b/layout_xml.md new file mode 100644 index 0000000..5b38697 --- /dev/null +++ b/layout_xml.md @@ -0,0 +1,117 @@ +# `layout.xml` Reference Documentation + +[TOC] + +## Introduction + +The layout.xml file is a crucial component of Magento 2's theming system. It provides a way to define the structure and +presentation of a webpage by specifying the block hierarchy, container layout, and block templates. This reference +documentation aims to explain the various elements and attributes that can be used in layout.xml files, along with their +functionalities and how they interact with the overall page rendering process. + +## Layout File Structure + +A layout.xml file is generally located in the `app/design/frontend/{Vendor}/{Theme}/Magento_Theme/layout` directory of a +Magento 2 theme. It follows a hierarchical structure where the root element is typically `` or ``, and it +can contain multiple nested elements like ``, ``, and ``. These elements describe +the various sections, blocks, and containers within the page layout. + +## Blocks + +Blocks are the building blocks of a layout file. They represent discrete sections of content or functionality on a +webpage. Each block is defined using the `` element, which must have a unique name attribute and can have +optional attributes like `class`, `template`, and `cacheable`. + +Example: + +```xml + + +``` + +In the above example: + +- `name` is a unique identifier for the block within the layout. +- `class` is the PHP class that implements the block's behavior. +- `template` specifies the template file used for rendering the block. + +## Containers + +Containers are used to group blocks and define their layout within a section of a webpage. Similar to blocks, containers +are represented by the `` element, which also requires a unique name attribute. Containers can have optional +attributes like `htmlTag`, `before`, `after`, and `label`. + +Example: + +```xml + + + + +``` + +In the above example, the `` element defines a container named `custom.container`. The `htmlTag` attribute +specifies the HTML tag to be used for rendering the container, and the `label` attribute provides a human-readable label +for the container. + +## References + +References allow blocks and containers to be rearranged or modified within the layout. They are represented by +the `` and `` elements. References are useful when a module needs to insert or +modify blocks or containers defined by other modules. + +Example: + +```xml + + + + +``` + +In the above example, the `` element references the existing container named `header.container` and +adds a new container named `custom.container` after the block named `logo` within the `header.container`. + +## Attributes + +Layout elements like blocks, containers, and references can have various attributes that provide additional control over +their behavior and appearance. Some commonly used attributes +include `htmlTag`, `before`, `after`, `label`, `as`, `output`, and `cacheable`. + +Example: + +```xml + + +``` + +In the above example: + +- `htmlTag` specifies the HTML tag to be used for rendering the block. +- `before` and `after` determine the block's position relative to other blocks or containers. +- `label` provides a human-readable label for the block. +- `as` allows the block to be referred to by an alias within the layout. +- `output` specifies the method used to render the block's output. +- `cacheable` controls whether the block's output is cacheable. + +## Examples + +To wrap up this reference documentation, here are a few examples that demonstrate the usage of layout.xml elements and +attributes: + +- [Example 1: Adding a new block](examples/example1.xml) +- [Example 2: Modifying an existing container](examples/example2.xml) +- [Example 3: Rearranging blocks using references](examples/example3.xml) + +Please refer to the above examples for a more hands-on understanding of how the layout.xml file can be used to define +the structure and presentation of a webpage in Magento 2. + +## Conclusion + +The layout.xml file is a powerful tool for defining the layout and structure of a webpage in Magento 2. By understanding +the elements, attributes, and their interactions, developers can create flexible and customizable page layouts. This +reference documentation should serve as a comprehensive guide to help you harness the full potential of the layout.xml +file in your Magento 2 theming endeavors. diff --git a/layouts-blocks-and-templates.md b/layouts-blocks-and-templates.md index e69de29..c6a5641 100644 --- a/layouts-blocks-and-templates.md +++ b/layouts-blocks-and-templates.md @@ -0,0 +1,154 @@ +# Layouts, Blocks, and Templates Documentation + +[TOC] + +## Introduction + +In Magento 2, layouts, blocks, and templates form the backbone of the presentation layer of your online store. +Understanding how these components work together is crucial for customizing the appearance and functionality of your +Magento store. This documentation provides an in-depth overview of layouts, blocks, and templates, including their +definitions, relationships, and usage examples. + +## Layouts + +### Definition + +Layouts in Magento 2 are XML files that define the structure and content of a page. They specify the positioning and +rendering of blocks and containers within a page. Layout files are located in the `app/design/frontend/` +or `app/design/adminhtml/` directory of your Magento installation. + +### Structure + +A layout file consists of a `` root node, which can contain multiple `` and `` nodes. +The `` nodes represent individual blocks of content, while the `` nodes define areas within the layout +where blocks can be dynamically added. + +### Usage Example + +Consider a scenario where you want to add a banner to the homepage of your Magento store. To achieve this, you would +create a custom layout file named `cms_index_index.xml` within your theme's layout directory. Within this file, you +would define a new block that corresponds to your banner, specifying its template and other attributes. + +```xml + + + + + + Welcome to our store! + + + + + +``` + +In this example, we've created a block named `custom_banner` and associated it with the `Vendor_Module::banner.phtml` +template. We've also passed a custom argument `banner_text` to the block, which can be accessed within the template. + +## Blocks + +### Definition + +Blocks in Magento 2 are PHP classes that handle the business logic and rendering of specific sections of a webpage. They +encapsulate data and functionality, which can be accessed and manipulated within the associated templates. Blocks are +instantiated and configured within layout files using the `` nodes. + +### Usage Example + +Suppose you want to create a block that displays a list of recently added products. You would create a custom PHP block +class, `RecentProducts`, which extends the `Magento\Framework\View\Element\Template` class. Within this class, you would +define a method, `getRecentProducts()`, that retrieves the necessary data and returns it to the template. + +```php +productCollectionFactory = $productCollectionFactory; + parent::__construct($context, $data); + } + + public function getRecentProducts() + { + $collection = $this->productCollectionFactory->create(); + $collection->addAttributeToSelect('*') + ->setOrder('created_at', 'DESC') + ->setPageSize(5); + + return $collection; + } +} +``` + +Now, in your layout file, you can add the `RecentProducts` block to the desired container. + +```xml + + +``` + +In the associated template file, `recent_products.phtml`, you can access the data returned by the `getRecentProducts()` +method using the `$block` object. + +```php +getRecentProducts(); + +foreach ($recentProducts as $product) { + // Display product details +} +``` + +## Templates + +### Definition + +Templates in Magento 2 are PHP files that handle the presentation logic of a block. They define the HTML structure and +styling for a specific block. Templates are associated with blocks within layout files using the `template` attribute of +the `` nodes. + +### Usage Example + +Consider the previous example of the `RecentProducts` block. In order to display the list of recent products, you would +create a template file named `recent_products.phtml` within your theme's template directory. Inside this file, you would +write the necessary HTML and PHP code to render the list. + +```html+php +
+

Recently Added Products

+ +
+``` + +In this template, we iterate over the `$recentProducts` array and generate the necessary HTML markup for each product. +We can access the product data and methods provided by the block using the `$block` object. + +## Conclusion + +Understanding the concepts of layouts, blocks, and templates is essential for customizing the appearance and +functionality of your Magento 2 store. Layouts define the structure of a page, blocks handle business logic and +rendering, and templates handle the presentation logic. By leveraging these components effectively, you can create a +highly customizable and visually appealing online store. diff --git a/logging.md b/logging.md index e69de29..15a2c04 100644 --- a/logging.md +++ b/logging.md @@ -0,0 +1,124 @@ +# Logging Documentation + +[TOC] + +## Introduction + +Logging is an essential process in software development that allows developers to collect and record information about +the execution of their code. It helps in troubleshooting, debugging, and monitoring applications. In this documentation, +we will explore the concept of logging, its importance, and how to effectively implement logging in PHP and Magento 2. + +## What is Logging? + +Logging is the practice of recording information about the execution of software applications. It involves capturing +relevant data and storing it in a structured format for analysis and reference. This information can include error +messages, warnings, debug statements, performance metrics, and more. + +Logging provides developers with a detailed record of events that occur during the execution of their code. This record +can be used to identify and diagnose issues, track user behavior, and monitor the health and performance of an +application. + +## Why is Logging Important? + +Logging plays a crucial role in software development for several reasons: + +- **Debugging**: When errors or unexpected behavior occur, logging helps developers understand what went wrong by + providing valuable information about the context in which the error occurred. +- **Troubleshooting**: Logging allows developers to trace the execution flow and identify potential bottlenecks or areas + of improvement. +- **Monitoring**: By logging performance metrics, developers can analyze the behavior of their application over time, + identify areas for optimization, and ensure the application meets its performance goals. +- **Compliance**: Logging can be essential for meeting regulatory requirements, such as tracking user actions or + maintaining an audit trail. + +Proper logging practices ensure that developers have the necessary information to diagnose and resolve issues quickly, +leading to more reliable and maintainable software. + +## Logging Levels + +Logging levels provide a way to categorize and prioritize different types of log messages based on their significance. +Common logging levels include: + +- **Debug**: Detailed information for debugging purposes, typically used during development. +- **Info**: General information about the execution flow or significant events. +- **Warning**: Indications that something unexpected happened, but the application can continue to function. +- **Error**: Errors that prevent the application from functioning correctly. +- **Critical**: Critical errors that require immediate attention and may result in the application's failure. + +By assigning appropriate logging levels to log messages, developers can filter and analyze logs based on their severity, +making it easier to focus on critical issues. + +## Logging in PHP + +PHP provides several logging mechanisms to capture and store log information. One commonly used approach is to utilize +the built-in logging functions provided by the PHP core, such as `error_log()` or `trigger_error()`. + +### Example: Basic Logging in PHP + +```php +// Log a message with the 'debug' level +error_log("Debug message", 3, "/path/to/logfile.log"); + +// Log an error message with the 'error' level +trigger_error("Something went wrong", E_USER_ERROR); +``` + +In the example above, the `error_log()` function is used to log a message with the level set to 'debug'. The log message +is written to the specified log file `/path/to/logfile.log`. Similarly, the `trigger_error()` function is used to log an +error message with the 'error' level. + +By adjusting the log levels and destinations, developers can control which messages are logged and where they are +stored. + +## Logging in Magento 2 + +Magento 2, a popular e-commerce platform, provides a robust logging system that allows developers to capture and manage +log messages from various parts of the application. + +Magento 2 uses the Monolog library, a powerful logging library, as its logging framework. Developers can take advantage +of Monolog's features, such as logging to different channels, formatting log messages, and filtering log levels. + +### Example: Logging in Magento 2 + +```php +use Psr\Log\LoggerInterface; + +class CustomClass +{ + protected $logger; + + public function __construct(LoggerInterface $logger) + { + $this->logger = $logger; + } + + public function doSomething() + { + // Log an info message + $this->logger->info('Something happened'); + + try { + // Business logic + } catch (\Exception $e) { + // Log an error message with the exception details + $this->logger->error('An error occurred', ['exception' => $e]); + } + } +} +``` + +In the example above, we have a custom class that utilizes Magento 2's logging capabilities. The `LoggerInterface` is +injected into the class's constructor, providing access to the logger instance. + +Inside the `doSomething()` method, an info message is logged using the `info()` method of the logger. Additionally, an +error message is logged within a try-catch block, including the exception details as additional context information. + +By leveraging Magento 2's logging system, developers can easily capture relevant information throughout the application +and analyze it using various tools and techniques. + +## Conclusion + +Logging is an indispensable part of software development, allowing developers to track and analyze the execution of +their code. By understanding the importance of logging, the different logging levels, and the available logging +mechanisms in PHP and Magento 2, developers can effectively implement logging in their applications. Proper logging +practices contribute to faster issue resolution, improved application performance, and enhanced debugging capabilities. diff --git a/magento-2-coding-standards.md b/magento-2-coding-standards.md index e69de29..acc296e 100644 --- a/magento-2-coding-standards.md +++ b/magento-2-coding-standards.md @@ -0,0 +1,188 @@ +# Magento 2 Coding Standards + +[TOC] + +## Introduction + +Magento 2 is a powerful e-commerce platform built on top of PHP. To ensure consistency and maintainability in codebases, +it's crucial to follow coding standards. This document outlines the coding standards specific to Magento 2, covering +various aspects of the development process. By adhering to these standards, developers can produce high-quality code +that is easy to read, understand, and maintain. + +## File Structure + +A well-organized file structure is crucial for a Magento 2 project. Following a consistent structure helps in easily +locating and managing files. The recommended file structure for a Magento 2 project is as follows: + +``` +app/ + code/ + / + / + Block/ + Controller/ + etc/ + Helper/ + Model/ + Setup/ + view/ + adminhtml/ + frontend/ + design/ + adminhtml/ + frontend/ + lib/ +``` + +## Naming Conventions + +Clear and consistent naming conventions contribute to code readability. Magento 2 follows the following conventions: + +- **Classes**: Use PascalCase for class names. For example: `MyCustomModuleBlock`. +- **Methods**: Use camelCase for method names. For example: `myMethod`. +- **Variables**: Use camelCase for variable names. For example: `myVariable`. +- **Constants**: Use uppercase snake_case for constants. For example: `MY_CONSTANT`. +- **Interfaces**: Use the `Interface` suffix for interface names. For example: `MyInterface`. +- **Traits**: Use the `Trait` suffix for trait names. For example: `MyTrait`. + +## Coding Style + +Consistent coding style improves code readability and maintainability. Magento 2 follows the PSR-12 coding standard, +with a few exceptions. Some key points to consider are: + +- **Indentation**: Use four spaces for indentation. +- **Line Length**: Limit lines to a maximum of 120 characters. +- **Braces**: Place opening braces on the same line, but closing braces on a new line. +- **Spacing**: Use a single space after control keywords (`if`, `else`, `for`, etc.), and around operators. + +Here's an example illustrating the coding style: + +```php +isEnabled()) { + $this->setTemplate('Vendor_Module::my_template.phtml'); + } + + return parent::_prepareLayout(); + } + + public function isEnabled() + { + return true; + } +} +``` + +## PHP Code Sniffers + +To enforce coding standards automatically, you can use PHP code sniffers like PHP_CodeSniffer or Magento's ECGM2. These +tools analyze the code against configured rules and highlight any violations. + +For example, to check coding standards using PHP_CodeSniffer, run the following command: + +``` +vendor/bin/phpcs --standard=PSR12 app/code/Vendor/Module/ +``` + +## Magento Specific Standards + +Magento 2 has its own set of coding standards specific to module development. Let's discuss a few important ones: + +### Module Structure + +A well-structured module enhances code organization. A typical module follows this structure: + +``` +app/ + code/ + / + / + etc/ + module.xml + registration.php +``` + +- **`etc/module.xml`**: Contains module configuration. +- **`registration.php`**: Registers the module. + +### Dependency Injection (DI) + +Magento 2 heavily relies on dependency injection to manage object dependencies. Following DI best practices ensures code +maintainability and testability. + +Here's an example of injecting a class dependency in the constructor: + +```php +dependency = $dependency; + } + + public function myMethod() + { + $this->dependency->doSomething(); + } +} +``` + +### Layout XML Files + +Layout XML files are used to define the structure of pages in Magento 2. Following standards for layout XML files +ensures consistency and readability. + +Here's an example of a layout XML file: + +```xml + + + + + + + + +``` + +### Database Schema + +Magento 2 uses declarative database schema definitions to manage database structures. Following the standards for +defining database schemas ensures maintainability and compatibility with upgrade scripts. + +Here's an example of a database schema definition: + +```xml + + + + + + + + +
+
+``` + +## Conclusion + +Adhering to Magento 2 coding standards ensures code consistency and maintainability. In this document, we covered file +structure, naming conventions, coding style, and Magento-specific standards. By following these guidelines, developers +can create high-quality Magento 2 code that is easier to understand, maintain, and scale. diff --git a/menu-xml.md b/menu-xml.md deleted file mode 100644 index e69de29..0000000 diff --git a/menu_xml.md b/menu_xml.md new file mode 100644 index 0000000..e8faf23 --- /dev/null +++ b/menu_xml.md @@ -0,0 +1,120 @@ +# `menu.xml` Reference Documentation + +[TOC] + +## Introduction + +The `menu.xml` file is an important configuration file in Magento 2 that defines the structure and content of menu items +in your store. It is located in the `etc/adminhtml` directory of your module or theme. This file is used to create or +modify menus in the Magento admin panel. + +## Menu Structure + +The `menu.xml` file uses XML tags to define the structure of the menu. Each menu item is created as a `` tag within +the `` tag. Here is an example of a simple menu structure: + +```xml + + + + + + + +``` + +In this example, we have two menu items: "Menu Item 1" and "Menu Item 2". + +- The `id` attribute uniquely identifies each menu item. It follows the format `Vendor_Module::menu_item_id`, + where `Vendor_Module` is the module name and `menu_item_id` is a unique identifier for the menu item. +- The `title` attribute sets the display name of the menu item. +- The `module` attribute specifies the module that owns the menu item. +- The `sortOrder` attribute determines the order in which the menu items are displayed. +- The `parent` attribute defines the parent menu item of the current menu item. The `parent` attribute value should be + set to the `id` of the parent menu item. +- The `action` attribute specifies the controller and action that will be executed when the menu item is clicked. +- The `resource` attribute restricts access to the menu item based on user roles and permissions. + +## Menu Item Configuration + +Each menu item can be further configured using additional XML tags within the `` tag. Here are some commonly used +configuration options: + +### ACL Resource + +The `` tag is used to specify the ACL resource that controls access to the menu item. It is recommended to +define a unique ACL resource for each menu item to manage user permissions effectively. For example: + +```xml + + + Vendor_Module::resource + +``` + +### Menu Item Icons + +You can add icons to your menu items using the `` tag's `resource` attribute. Magento 2 supports a wide range of +icons provided by the Font Awesome library. For example: + +```xml + + + Vendor_Module::resource + + fa-icon-name + + +``` + +Replace `fa-icon-name` with the desired Font Awesome icon class name. + +### Menu Item Submenus + +You can create submenus by adding multiple levels of menu items. Each submenu is defined by adding a nested `` tag +within the parent menu item's `` tag. For example: + +```xml + + + + Vendor_Module::resource + + +``` + +In this example, "Menu Item 6" is a submenu of "Menu Item 5". + +## Conclusion + +The `menu.xml` file is a crucial component in defining the structure and content of menus in the Magento admin panel. By +understanding its structure and configuration options, you can create customized menus that fit your specific needs. Use +the provided examples and code snippets as a reference to help you create and modify menu items effectively. diff --git a/module-development.md b/module-development.md index e69de29..39a4065 100644 --- a/module-development.md +++ b/module-development.md @@ -0,0 +1,449 @@ +# Module Development Documentation + +[TOC] + +## Introduction + +This documentation serves as a guide for module development in Magento 2, specifically focusing on PHP-based module +development. It assumes that you have a working knowledge of PHP and familiarity with Magento 2's architecture and +concepts. + +## Module Structure + +A Magento 2 module is organized in the following directory structure: + +``` +app +└── code + └── Vendor + └── Module + ├── etc + │ ├── module.xml + │ └── other_configuration_files.xml + ├── Model + │ ├── ResourceModel + │ └── other_model_classes.php + ├── Controller + │ └── other_controller_classes.php + ├── Block + │ └── other_block_classes.php + ├── view + │ ├── frontend + │ └── adminhtml + └── other_files_and_directories +``` + +Here, `Vendor` refers to your company or organization name, and `Module` is the name of your module. You should replace +these placeholders with appropriate names. + +The `etc` directory contains module configuration files, such as `module.xml` that defines the module's identity. + +The `Model` directory contains model classes and resource models, while the `Controller` directory holds controller +classes for handling requests. + +The `Block` directory contains block classes responsible for rendering templates. + +The `view` directory houses frontend and adminhtml directories, which contain layout XML files, templates, and other +view-related files. + +## Module Registration + +To register your module with Magento 2, you need to create a `module.xml` file in your module's `etc` directory. Here's +an example `module.xml`: + +```xml + + + + + + + + +``` + +In this example, `Vendor_Module` is the module's name, and `1.0.0` is the version. The `` tag defines any +modules that your module depends on. In this case, it depends on `Magento_Cms`. + +## Module Configuration + +To add configuration settings for your module, create a configuration XML file in your module's `etc` directory. For +example, if your module is named `Vendor_Module`, create a file named `module_config.xml`. + +Here's an example of a `module_config.xml` file: + +```xml + + + + + + 1 + value + + + + +``` + +In this example, the module's configuration settings are placed under the `` tag. You can define any +number of settings within the `` tag. + +To access these settings in your module code, you can use the following code snippet: + +```php +$isEnabled = $this->scopeConfig->getValue('vendor_module/general/enabled'); +``` + +Here, `$this->scopeConfig` is an instance of `\Magento\Framework\App\Config\ScopeConfigInterface`. + +## Event Observers + +Magento 2 provides an event-driven architecture, allowing modules to observe and react to specific events that occur +during the application's execution. To create an event observer in your module, follow these steps: + +1. Create an XML file named `events.xml` in your module's `etc` directory. +2. Define your event observer inside this file. Here's an example: + +```xml + + + + + + +``` + +In this example, we're observing the `checkout_onepage_controller_success_action` event and linking it to +the `Vendor\Module\Observer\CheckoutSuccessObserver` class. + +3. Implement the observer class with the necessary logic. Here's an example: + +```php +resultPageFactory = $resultPageFactory; + } + + public function execute() + { + $resultPage = $this->resultPageFactory->create(); + return $resultPage; + } +} +``` + +In this example, the `execute()` method returns a `Page` result, which can be used to render a page template. + +3. Register your controller in your module's `routes.xml` file. Here's an example: + +```xml + + + + + + + + +``` + +In this example, we're registering the `Vendor\Module\Controller\Custom\CustomController` under the route `custom`. + +## Block and Template Files + +Blocks are responsible for providing data to templates and rendering them in Magento 2. To create a block and template +file, follow these steps: + +1. Create a PHP class file for your block, e.g., `CustomBlock.php`. +2. Implement the necessary logic inside the class. Here's an example: + +```php +getCustomData(); ?> +``` + +In this example, `$block` refers to an instance of `CustomBlock`. + +4. Use your block and template in a layout XML file. Here's an example: + +```xml + + + + + + + + +``` + +In this example, we're adding the `custom.block` block to the `content` container and using the `custom_template.phtml` +template. + +## Database Setup + +Magento 2 uses database setup scripts to create and modify database tables and perform other setup tasks. To create a +database setup script, follow these steps: + +1. Create a file named `InstallSchema.php` inside your module's `Setup` directory. +2. Implement the necessary logic inside the class. Here's an example: + +```php +startSetup(); + + $table = $setup->getConnection() + ->newTable($setup->getTable('custom_table')) + ->addColumn( + 'entity_id', + \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, + null, + ['identity' => true, 'nullable' => false, 'primary' => true], + 'Entity ID' + ) + ->addColumn( + 'name', + \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, + 255, + ['nullable' => false], + 'Name' + ) + ->addColumn( + 'created_at', + \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, + null, + ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT], + 'Created At' + ) + ->setComment('Custom Table'); + + $setup->getConnection()->createTable($table); + + $setup->endSetup(); + } +} +``` + +In this example, we're creating a table named `custom_table` with three columns: `entity_id`, `name`, and `created_at`. + +3. Run the setup upgrade command to apply your schema changes: + +```shell +bin/magento setup:upgrade +``` + +## API Integration + +Magento 2 provides a robust framework for building and integrating APIs. To create a custom API endpoint in your module, +follow these steps: + +1. Create a PHP class file for your API endpoint, e.g., `CustomApi.php`. +2. Implement the necessary logic inside the class. Here's an example: + +```php + + + + + + + + + +``` + +In this example, we're defining a route for the `GET` HTTP method, with the URL pattern `/V1/custom/:id`. The `class` +attribute refers to your API implementation class, and the `method` attribute specifies the method to be called. + +## Custom GraphQL Types + +Magento 2 supports GraphQL, a modern API query language. To create a custom GraphQL type in your module, follow these +steps: + +1. Create a PHP class file for your custom GraphQL type, e.g., `CustomType.php`. +2. Implement the necessary logic inside the class. Here's an example: + +```php + + + + + + +``` + +In this example, the observer `MyObserver` is registered for the `some_event_name` event. + +## Dispatching Events + +To trigger your observer, you need to dispatch the corresponding event. Magento 2 provides various ways to dispatch +events, depending on the context and purpose. + +Here's an example of dispatching an event: + +```php +use Magento\Framework\Event\ManagerInterface as EventManager; + +class SomeClass +{ + private $eventManager; + + public function __construct(EventManager $eventManager) + { + $this->eventManager = $eventManager; + } + + public function doSomething() + { + // Some business logic + + $eventData = ['param1' => 'value1', 'param2' => 'value2']; + + $this->eventManager->dispatch('some_event_name', $eventData); + + // Continue with other operations + } +} +``` + +In this example, the event with the name `some_event_name` is dispatched using the `$eventManager->dispatch()` method. +The `$eventData` array can contain any additional data you want to pass to the observer. + +## Observer Execution + +When an event is dispatched, Magento 2 will automatically trigger the `execute()` method of all registered observers for +that event. The order of execution is determined by the order in which the observers are registered. + +If you have multiple observers for the same event, you can define the execution order by setting the `sequence` +attribute in the observer registration. Observers with lower sequence values will execute first. + +```xml + + + +``` + +In this example, `FirstObserver` will execute before `SecondObserver` due to the lower sequence value. + +## Observer Example + +Let's consider a practical example to illustrate how observers work. Suppose you want to send a notification email to +the customer whenever a new order is placed in your Magento 2 store. + +First, create an observer class to handle the logic: + +```php +namespace Vendor\Module\Observer; + +use Magento\Framework\Event\ObserverInterface; +use Magento\Framework\Mail\Template\TransportBuilder; +use Magento\Store\Model\StoreManagerInterface; + +class NewOrderObserver implements ObserverInterface +{ + private $transportBuilder; + private $storeManager; + + public function __construct( + TransportBuilder $transportBuilder, + StoreManagerInterface $storeManager + ) { + $this->transportBuilder = $transportBuilder; + $this->storeManager = $storeManager; + } + + public function execute(\Magento\Framework\Event\Observer $observer) + { + $order = $observer->getData('order'); + + $storeId = $order->getStoreId(); + $store = $this->storeManager->getStore($storeId); + + $templateVars = [ + 'order' => $order, + 'store' => $store + ]; + + $this->transportBuilder->setTemplateIdentifier('new_order_email_template') + ->setTemplateOptions(['area' => 'frontend', 'store' => $storeId]) + ->setTemplateVars($templateVars) + ->setFrom('general') + ->addTo($order->getCustomerEmail()) + ->getTransport() + ->sendMessage(); + } +} +``` + +In this example, the `execute()` method retrieves the order object from the observer data and sends an email using +the `TransportBuilder`. + +Next, register the observer in your module's `etc/events.xml` file: + +```xml + + + + + + +``` + +Now, whenever a new order is placed (`sales_order_place_after` event), the `NewOrderObserver` will be triggered, sending +an email notification to the customer. + +## Conclusion + +Observers in Magento 2 provide a powerful way to customize and extend the functionality of your store without modifying +the core code. By registering observers for specific events, you can execute custom code at the right time and integrate +with other modules seamlessly. This documentation has covered the basics of observers, including their implementation, +registration, and execution. With this knowledge, you can leverage observers to build flexible and customizable +solutions in your Magento 2 projects. diff --git a/overview-of-magento-2-apis.md b/overview-of-magento-2-apis.md index e38a10e..d8c7f4e 100644 --- a/overview-of-magento-2-apis.md +++ b/overview-of-magento-2-apis.md @@ -1,44 +1,131 @@ -# Magento 2 API Overview +# Magento 2 APIs Overview -- [Magento 2 API Overview](#magento-2-api-overview) - * [REST and SOAP APIs](#rest-and-soap-apis) - * [Endpoints](#endpoints) - * [Authentication](#authentication) - * [Usage Limits](#usage-limits) - * [Asynchronous API](#asynchronous-api) - * [GraphQL](#graphql) +[TOC] -Magento 2 APIs, commonly referred to as web APIs, allow third-party services to integrate with Magento using REST ( -Representational State Transfer) and SOAP (Simple Object Access Protocol). These APIs ensure that data can be seamlessly -passed between Magento and other systems, such as ERP systems, CRM platforms, mobile apps, and more. +## Introduction -## REST and SOAP APIs +Magento 2 is a powerful ecommerce platform that provides a wide range of APIs for developers to build and extend their +online stores. These APIs enable developers to interact with various components of the Magento system, such as products, +customers, orders, and more. In this documentation, we will provide an overview of the different types of APIs available +in Magento 2 and how to use them effectively. -REST and SOAP are two different approaches to network communication in web services. REST APIs use HTTP methods to -retrieve and send data and are typically easier to work with. SOAP, on the other hand, is a protocol with a defined -standard to communicate, providing a robust and extensible option. +## Types of APIs in Magento 2 -## Endpoints +Magento 2 offers three main types of APIs: -Magento 2 provides numerous API endpoints, segregated by modules such as customers, products, orders, and more. Each -endpoint corresponds to a specific type of resource. +1. **Web APIs**: These APIs allow remote systems to interact with the Magento 2 platform using HTTP(S) protocols. Web + APIs are based on Representational State Transfer (REST) and support both JSON and XML data formats. They provide + CRUD operations (Create, Read, Update, Delete) for various entities in the Magento system. Web APIs are ideal for + building integrations with third-party systems, mobile apps, or custom frontend applications. -## Authentication +2. **Service Contracts**: Service Contracts are PHP interfaces that define the public API of a module. They provide a + more structured and reliable way to interact with Magento 2 modules compared to direct database operations or custom + SQL queries. Service Contracts enforce a separation of concerns between the module’s business logic and its data + storage and retrieval. They are mainly used by other modules within the Magento system. -Magento 2 supports both token-based authentication and OAuth-based authentication, depending on the level of access and -type of integration. +3. **GraphQL APIs**: GraphQL is an alternative to REST for querying and manipulating data. It provides a flexible and + efficient way to request only the specific data needed, reducing the amount of data sent over the wire. GraphQL APIs + in Magento 2 are built on top of the underlying Service Contracts and provide a powerful tool for frontend developers + to retrieve data from the Magento system. -## Usage Limits +## Web APIs -While Magento 2 Open Source does not impose any specific usage limits on its APIs, your server or hosting provider -might. Magento 2 Commerce can be configured to enforce customizable API rate limiting. +Magento 2 Web APIs provide a comprehensive set of endpoints for interacting with different entities, including products, +customers, orders, categories, and more. Each entity has its own set of API endpoints that follow a consistent URL +structure. For example, to retrieve a list of products, you would use the `/V1/products` endpoint. -## Asynchronous API +Web APIs are authenticated using the OAuth 1.0a protocol or token-based authentication. OAuth 1.0a provides a secure +mechanism for authenticating external systems with the Magento platform. Token-based authentication, on the other hand, +is simpler to implement and doesn't require the complex OAuth flow. -To optimize performance and user experience, Magento 2.3 introduced Asynchronous API. This enables requests to be -processed in the background, freeing up the server to handle other requests. +Here's an example of how to retrieve a list of products using a token-based authentication: -## GraphQL +```php +$token = 'your_token_here'; +$baseUrl = 'https://your_magento_store.com/rest/V1'; -Starting from Magento 2.3, Magento also supports GraphQL, an open-source data query and manipulation language for APIs, -providing a more efficient alternative to traditional REST/SOAP. +$ch = curl_init(); +curl_setopt($ch, CURLOPT_URL, $baseUrl . '/products'); +curl_setopt($ch, CURLOPT_HTTPHEADER, [ + 'Authorization: Bearer ' . $token, + 'Content-Type: application/json' +]); +curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + +$response = curl_exec($ch); +curl_close($ch); + +$result = json_decode($response, true); +``` + +## Service Contracts + +Service Contracts in Magento 2 provide a standardized way to interact with module functionality. They define a set of +PHP interfaces that represent the public API of a module. By adhering to these interfaces, developers ensure that their +code is compatible with future versions of Magento and other third-party modules. + +For example, to create a new customer using Service Contracts, you would use the `CustomerRepositoryInterface`: + +```php +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\CustomerInterfaceFactory; + +class CustomerCreator +{ + private $customerRepository; + private $customerFactory; + + public function __construct( + CustomerRepositoryInterface $customerRepository, + CustomerInterfaceFactory $customerFactory + ) { + $this->customerRepository = $customerRepository; + $this->customerFactory = $customerFactory; + } + + public function createCustomer($data) + { + $customer = $this->customerFactory->create(); + // Set customer data + + $customer = $this->customerRepository->save($customer); + return $customer; + } +} +``` + +## GraphQL APIs + +Magento 2's GraphQL APIs provide a flexible and efficient way to retrieve and manipulate data. With GraphQL, frontend +developers can request only the specific data they need, reducing the number of requests and the amount of data +transferred between the server and client. + +To retrieve a list of products using GraphQL, you would write a query like this: + +```graphql +{ + products(search: "t-shirt") { + items { + id + name + price { + regularPrice { + amount { + value + currency + } + } + } + } + } +} +``` + +This query will return a list of products matching the search term "t-shirt" along with their names and prices. + +## Conclusion + +Magento 2 provides a powerful set of APIs that enable developers to build and extend their online stores. Web APIs, +Service Contracts, and GraphQL APIs offer different ways to interact with the Magento system, depending on the use case +and requirements of your project. By leveraging these APIs effectively, you can create custom integrations, build mobile +apps, and enhance the functionality of your Magento 2 store. diff --git a/overview-of-magento-2-development.md b/overview-of-magento-2-development.md index 9e3cf63..07b02ea 100644 --- a/overview-of-magento-2-development.md +++ b/overview-of-magento-2-development.md @@ -1,49 +1,285 @@ # Magento 2 Development Overview -- -- [Magento 2 Development Overview](#magento-2-development-overview) - * [Development Principles](#development-principles) - * [Environment Setup](#environment-setup) - * [Theme Development](#theme-development) - * [Extension Development](#extension-development) - * [Customization Techniques](#customization-techniques) - * [Testing](#testing) - * [Performance Optimization](#performance-optimization) -Magento 2 development encompasses a broad range of activities, from theme and extension development to performance -optimization and customization of the core functionality. Magento 2 offers flexibility, extensibility, and a rich set of -out-of-the-box features that can be leveraged to develop a wide range of eCommerce solutions. +[TOC] -## Development Principles +## Introduction -Magento 2 adheres to the principles of modularity, scalability, and extensibility. It leverages an architecture that -encourages reuse, loose coupling, and configuration over coding. +Welcome to the overview of Magento 2 development! In this document, we will provide you with a comprehensive +understanding of the key concepts, tools, and techniques involved in developing with Magento 2. Whether you are a +seasoned Magento developer or new to the platform, this documentation will serve as a valuable resource to further +enhance your skills and knowledge. -## Environment Setup +## Architecture -Setting up a proper Magento 2 development environment is crucial. This typically includes a local development server ( -like XAMPP, WAMP, or MAMP), a PHP IDE or editor, and command-line tools like Composer and Git. +Magento 2 follows a modular architecture that allows for easy customization and extension. The core functionality is +divided into separate modules, which can be customized or extended as per your business requirements. The modular +structure also promotes code reusability and maintainability. -## Theme Development +## Modules -Magento 2 theme development involves creating a visual design for your eCommerce store. You can create a new theme from -scratch, or extend and customize an existing theme. +Modules are the building blocks of Magento 2. They encapsulate specific functionalities and can be easily added, +removed, or disabled. A module consists of various components such as controllers, models, blocks, and templates. -## Extension Development +To create a custom module, you need to define its structure in the `app/code` directory. Let's take an example of a +module named `MyCompany_MyModule`. -Extensions or modules in Magento 2 allow you to add new functionality or modify existing functionality. Magento 2 has a -modular architecture, allowing developers to customize and extend the platform without altering the core codebase. +```markdown +app/ +code/ +MyCompany/ +MyModule/ +etc/ +module.xml +registration.php +``` -## Customization Techniques +The `module.xml` file defines the module's configuration, while `registration.php` registers the module with Magento. -Magento 2 provides various customization techniques including plugins (Interceptors), observers/events, and rewrites. It -encourages developers to follow the 'do not modify core' principle. +## Themes -## Testing +Themes in Magento 2 control the visual appearance of your store. They consist of various components such as layouts, +templates, CSS, and JavaScript files. You can create a custom theme to give your store a unique look and feel. -Testing is an integral part of Magento 2 development. Magento 2 provides a testing framework that supports various types -of tests, including unit tests, integration tests, functional tests, and more. +To create a custom theme, define its structure in the `app/design` directory. For example, to create a theme +named `MyCompany/mytheme`, the directory structure would be as follows: -## Performance Optimization +```markdown +app/ +design/ +frontend/ +MyCompany/ +mytheme/ +etc/ +view.xml +registration.php +``` -Magento 2 offers a range of performance optimization options, such as Full Page Cache (FPC), Varnish, Redis, and -performance toolkit for benchmarking your site's performance. +The `view.xml` file allows you to configure various aspects of the theme, such as image sizes, widgets, and responsive +behavior. + +## Layouts + +Layouts in Magento 2 define the structure and composition of the pages. They are XML files that specify the arrangement +of blocks and containers on a page. Layout files are located in the `app/design` directory. + +Here's an example of a layout file named `catalog_product_view.xml`: + +```xml + + + + + + + +``` + +In this example, we remove the SKU block from the product page and move the review block before all other blocks within +the `product.info.main` container. + +## Blocks + +Blocks in Magento 2 encapsulate reusable components that provide specific functionalities. They are PHP classes +responsible for handling business logic and generating HTML output. Blocks can be referenced and manipulated within +layout XML files. + +Here's an example of a block class named `MyCompany\MyModule\Block\Product\View`: + +```php +_coreRegistry->registry('current_product'); + } +} +``` + +In this example, the block extends the `Template` class and provides a method to retrieve the current product from the +registry. + +## Models + +Models in Magento 2 represent the business entities and handle data manipulation. They interact with the database and +provide an interface for retrieving, creating, updating, and deleting records. + +Here's an example of a model class named `MyCompany\MyModule\Model\Product`: + +```php +_init(\MyCompany\MyModule\Model\ResourceModel\Product::class); + } +} +``` + +In this example, the model extends the `AbstractModel` class and initializes the resource model. + +## Controllers + +Controllers in Magento 2 handle incoming HTTP requests and generate responses. They are responsible for executing the +requested action and rendering the appropriate view. Controllers can be extended or overridden to modify the default +behavior. + +Here's an example of a controller class named `MyCompany\MyModule\Controller\Product\View`: + +```php +resultPageFactory = $resultPageFactory; + } + + public function execute() + { + return $this->resultPageFactory->create(); + } +} +``` + +In this example, the controller extends the `Action` class and uses the `PageFactory` to generate a result page. + +## Events and Observers + +Events and observers in Magento 2 provide a way to extend or modify the default behavior without modifying the core +code. Events are dispatched at specific points in the code, and observers listen for these events and execute custom +logic. + +Here's an example of an event dispatch in Magento 2: + +```php +eventManager = $eventManager; + } + + public function execute() + { + // Dispatch the event + $this->eventManager->dispatch('my_module_product_view', ['product' => $product]); + } +} +``` + +An observer can then listen to this event and perform custom actions. For example: + +```php +getData('product'); + // Perform custom logic + } +} +``` + +## Plugins + +Plugins in Magento 2 provide a way to modify or extend the behavior of public class methods. They allow you to intercept +method calls and perform custom actions before, after, or around the original method execution. + +Here's an example of a plugin class: + +```php + + +Magento 2 provides a comprehensive set of web APIs that allow external systems to interact with the platform. Web APIs +enable you to create, read, update, and delete data using standard HTTP methods. + +To use web APIs, you need to define your API endpoints and specify the required authentication and permissions. Magento +provides a range of authentication methods such as OAuth, token-based, and guest access. + +For example, to create a custom API endpoint to retrieve product information, you would define the endpoint in a +module's `etc/webapi.xml` file and implement the corresponding interface and class. + +## Testing + +Magento 2 emphasizes the importance of testing by providing a robust testing framework. The framework includes unit +tests, integration tests, and functional tests. Writing tests for your custom modules and themes helps ensure the +stability and reliability of your codebase. + +Magento 2 uses PHPUnit as the testing framework. You can write tests for your modules in the `Test/Unit` directory and +execute them using the command-line interface. + +## Conclusion + +This overview of Magento 2 development has provided you with a solid foundation to delve deeper into the various aspects +of Magento 2. Armed with this knowledge, you are now equipped to create custom modules, themes, and extensions, and +harness the power of Magento 2 to build scalable and robust e-commerce solutions. Happy coding! diff --git a/overview-of-magento-2.md b/overview-of-magento-2.md index f96b3ea..036277d 100644 --- a/overview-of-magento-2.md +++ b/overview-of-magento-2.md @@ -1,79 +1,99 @@ -# Overview of Magento 2 +# Magento 2 Overview -- [Introduction](#introduction) -- [Architecture](#architecture) -- [Extensibility](#extensibility) -- [Performance and Scalability](#performance-and-scalability) -- [Tools and Testing](#tools-and-testing) -- [Community](#community) +[TOC] - +This documentation provides an overview of Magento 2, a widely used and powerful e-commerce platform built on PHP. +Magento 2 offers a plethora of features, functionalities, and customization options to create robust and scalable online +stores. This guide will introduce you to the key components and concepts of Magento 2, providing you with a solid +foundation for further exploration. -## Introduction +## Architecture -Magento 2, the latest version of the open-source eCommerce platform Magento, presents an array of significant upgrades -and additions to its already robust predecessor, Magento 1. These enhancements are designed to simplify the user -experience, boost the performance of online stores, and provide greater flexibility and control to developers. This -version retains its fundamental ethos as a highly customizable, scalable, and feature-rich solution that empowers -businesses of all sizes. +Magento 2 follows a modular architecture that promotes flexibility and extensibility. The core functionality is divided +into various modules that can be enabled or disabled as per the requirements of your online store. Additionally, custom +modules can be developed to extend or modify the existing functionality. Let's take a look at the key architectural +components: - +### Modules -## Architecture -Built primarily using PHP, Magento 2 employs the MySQL/MariaDB relational database management system and the Zend -Framework. It utilizes a service-contract-based architecture that separates the HTML view from business logic. This is -particularly important in maintaining code modularity and ensuring backward compatibility, which is vital for -customizing and extending the functionality of your eCommerce platform without disrupting existing features. +Modules are the building blocks of Magento 2. Each module encapsulates a specific functionality, such as catalog +management, checkout, customer management, etc. They define the structure, behavior, and available APIs of their +respective domains. Modules can depend on other modules, creating a modular and flexible system. You can develop your +own modules or leverage existing ones from the Magento Marketplace. + +### Themes + +Themes define the visual appearance of your Magento 2 store. A theme includes various components like templates, +layouts, CSS, and JavaScript files. Magento 2 provides a default theme, but you can customize it or create your own +theme to suit your brand and requirements. Customizing the theme allows you to create a unique and personalized shopping +experience for your customers. + +## Key Concepts + +To effectively work with Magento 2, it's crucial to understand the key concepts that underpin its architecture and +functionality. Let's explore some of these concepts: + +### Stores, Websites, and Store Views + +A Magento 2 installation can have multiple stores, each representing a separate website or brand. Each store can have +multiple websites, and each website can have multiple store views. Store views define different languages, currencies, +and other localized settings. This hierarchical structure allows you to manage multiple online stores from a single +Magento 2 installation. + +### Entity-Attribute-Value (EAV) Database Model + +The EAV database model is employed by Magento 2 to store and manage a wide range of data. It allows for flexible and +scalable data storage by providing a dynamic way to add attributes to entities. For example, the product catalog uses +the EAV model to store product attributes like name, SKU, price, etc. Understanding the EAV model helps in effectively +querying and manipulating data in Magento 2. -Magento 2 uses a conventional Model-View-Controller (MVC) pattern for requests handling. However, it also introduces a -new pattern called Model-View-ViewModel (MVVM) in the layout rendering process to simplify and streamline the generation -of HTML content. +### Dependency Injection (DI) - +Magento 2 extensively utilizes the concept of dependency injection to manage object dependencies. Dependency injection +allows for loose coupling, easier testing, and better maintainability of code. The DI mechanism in Magento 2 relies on +XML configuration files and constructor injection. Here's an example of constructor injection in a custom module: -## Extensibility -Magento 2 further extends its predecessor's commitment to extensibility through a greater emphasis on object-oriented -programming and dependency injection. It offers a flexible system for creating themes, enabling developers to customize -the appearance of their eCommerce stores, and an expansive suite of APIs for integrating external systems. +```php +namespace Vendor\Module\Model; -Modular code allows developers to modify or replace core components without altering the core codebase itself. This -extends to payment gateways, shipping methods, languages, and more, making Magento 2 adaptable to a wide range of -business needs. +use Magento\Framework\App\Config\ScopeConfigInterface; - +class MyModel +{ + private $scopeConfig; -## Performance and Scalability -Performance improvements in Magento 2 include better indexing, enhanced browser caching for static content, and -full-page caching. It also supports Varnish out-of-the-box, which significantly reduces server load and enhances site -performance. + public function __construct(ScopeConfigInterface $scopeConfig) + { + $this->scopeConfig = $scopeConfig; + } -Magento 2 includes features to support scalability, such as horizontal scaling via the use of multiple databases. You -can have separate databases for order management, product management, and checkout, thus enhancing the scalability and -performance of your eCommerce platform. + // ... +} +``` - +### Service Contracts -## Tools and Testing -Magento 2 introduces new tools for developers like a Component Manager, a stand-alone installer, and command-line -interface tools. These tools allow developers to manage modules, install Magento, and clear cache, re-index, and more -without accessing the admin interface. +Service contracts define a set of API interfaces that expose the functionality of a module. They provide a standardized +way to interact with the underlying business logic without directly accessing the implementation details. Service +contracts enhance the stability and compatibility of Magento 2, allowing for easy upgrades and third-party integrations. +For example, the `ProductRepositoryInterface` provides methods to create, read, update, and delete products. -Testing is another area where Magento 2 shines, providing built-in tools that support unit tests, integration tests, -functional tests, and performance tests. This is a significant improvement over its predecessor, enabling a more -reliable, robust, and high-quality codebase. +```php +namespace Magento\Catalog\Api; -In conclusion, Magento 2 is a comprehensive solution designed to provide both businesses and developers with the tools, -flexibility, and power to create compelling, high-performing eCommerce experiences. Whether you're working with a small -business or a multi-national enterprise, Magento 2 offers the necessary features and capabilities to deliver outstanding -results. +use Magento\Catalog\Api\Data\ProductInterface; - +interface ProductRepositoryInterface +{ + public function save(ProductInterface $product); + public function getById($id); + // ... +} +``` -## Community -Perhaps one of the most remarkable aspects of Magento 2 is its vibrant, global community. It comprises developers, -designers, business owners, and eCommerce specialists who actively contribute to the growth and improvement of the -platform. This network of professionals shares insights, offers advice, develops extensions, and patches bugs, fostering -an environment of collaboration and mutual growth. With resources like the Magento Forum, Magento Stack Exchange, and -numerous blogs and podcasts, you can find answers to your questions, keep abreast of the latest developments, and -continuously enhance your Magento 2 knowledge and skills. +## Conclusion +This overview provides you with a glimpse into the architecture and key concepts of Magento 2. Understanding these +components and concepts is essential for building and customizing online stores on the Magento 2 platform. You can now +delve deeper into each topic and explore the vast capabilities that Magento 2 offers for e-commerce development. Happy +coding! diff --git a/overview-of-the-architectural-components.md b/overview-of-the-architectural-components.md index e69de29..2fbfd3a 100644 --- a/overview-of-the-architectural-components.md +++ b/overview-of-the-architectural-components.md @@ -0,0 +1,169 @@ +# Overview of Architectural Components + +[TOC] + +This documentation provides an overview of the architectural components used in PHP and Magento 2 development. +Understanding these components is crucial for building robust and scalable applications. We will discuss the key +architectural components and their roles in the software development process. + +## Model-View-Controller (MVC) Pattern + +The Model-View-Controller (MVC) pattern is a widely adopted architectural pattern for designing web applications. It +separates the application into three interconnected components: Model, View, and Controller. + +### Model + +The Model represents the data and business logic of the application. It is responsible for handling data storage, +retrieval, and manipulation. In Magento 2, Models are typically implemented as PHP classes that interact with the +database. + +Example: + +```php +namespace Vendor\Module\Model; + +use Magento\Framework\Model\AbstractModel; + +class Product extends AbstractModel +{ + protected function _construct() + { + $this->_init(\Vendor\Module\Model\ResourceModel\Product::class); + } + + // Model methods +} +``` + +### View + +The View is responsible for presenting the data to the user. It generates the HTML output and handles user interactions. +In Magento 2, Views are implemented using XML and PHTML templates. + +Example (XML layout file): + +```xml + + + + + + + + +``` + +### Controller + +The Controller receives user requests, processes them, and interacts with the Model and View components. It is +responsible for handling business logic, such as validating input, executing actions, and returning responses. In +Magento 2, Controllers are implemented as PHP classes. + +Example: + +```php +namespace Vendor\Module\Controller\Product; + +use Magento\Framework\App\Action\Action; +use Magento\Framework\App\Action\Context; +use Vendor\Module\Model\ProductFactory; + +class View extends Action +{ + protected $productFactory; + + public function __construct(Context $context, ProductFactory $productFactory) + { + parent::__construct($context); + $this->productFactory = $productFactory; + } + + public function execute() + { + $productId = $this->getRequest()->getParam('id'); + $product = $this->productFactory->create()->load($productId); + + // Process and pass data to the View + + return $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_PAGE); + } +} +``` + +## Service Contracts + +Service Contracts provide a standardized interface for interacting with system components. They define a set of methods +that can be called by other components, ensuring consistency and flexibility in the system architecture. Magento 2 +extensively uses Service Contracts to decouple modules and facilitate interoperability. + +Example (Service Contract interface): + +```php +namespace Vendor\Module\Api; + +interface ProductServiceInterface +{ + /** + * Get product by ID + * + * @param int $productId + * @return \Vendor\Module\Api\Data\ProductInterface + * @throws \Magento\Framework\Exception\NoSuchEntityException + */ + public function getProduct($productId); + + // Other methods +} +``` + +## Dependency Injection (DI) + +Dependency Injection (DI) is a design pattern used to manage component dependencies and improve code maintainability and +testability. In Magento 2, DI is implemented using configuration files and annotations. It allows components to request +dependencies from a centralized container, reducing coupling and enabling module customization. + +Example (DI configuration file): + +```xml + + + + +``` + +Example (DI annotation): + +```php +namespace Vendor\Module\Model; + +use Vendor\Module\Api\ProductServiceInterface; + +class ProductService implements ProductServiceInterface +{ + /** + * @var \Vendor\Module\Model\ProductFactory + */ + protected $productFactory; + + /** + * @param \Vendor\Module\Model\ProductFactory $productFactory + */ + public function __construct(ProductFactory $productFactory) + { + $this->productFactory = $productFactory; + } + + // Implement interface methods +} +``` + +## Conclusion + +Understanding the architectural components used in PHP and Magento 2 development is crucial for building scalable and +maintainable applications. The Model-View-Controller (MVC) pattern provides a clear separation of concerns, while +Service Contracts and Dependency Injection (DI) enable modular and customizable development. By leveraging these +architectural components, developers can create robust and flexible applications that meet the needs of their clients or +businesses. diff --git a/performance-best-practices.md b/performance-best-practices.md index e69de29..4b533d6 100644 --- a/performance-best-practices.md +++ b/performance-best-practices.md @@ -0,0 +1,186 @@ +# Performance Best Practices + +[TOC] + +This document aims to provide a comprehensive guide on performance best practices for PHP and Magento 2. By following +these recommendations, you can optimize the performance of your PHP code and improve the overall speed and efficiency of +your Magento 2 application. The guidelines discussed here are based on industry best practices and can help you achieve +faster page load times, reduce server load, and enhance the overall user experience. + +## Caching + +Caching is an essential technique for improving performance in PHP and Magento 2 applications. By caching frequently +accessed data, you can avoid the need to generate the same content repeatedly, reducing the load on your server and +improving response times. There are several caching mechanisms available in Magento 2: + +### Full Page Caching + +Magento 2 provides built-in full page caching, which can significantly improve the performance of your store. You can +enable full page caching from the Magento Admin panel under **Stores > Configuration > Advanced > System > Full Page +Cache**. This feature caches complete HTML pages, bypassing expensive database queries and PHP rendering for subsequent +requests. + +### Object Caching + +Magento 2 supports various object caching mechanisms, such as Redis and Memcached, which can be configured from the +Magento Admin panel. These caching systems store PHP objects in memory, allowing for faster retrieval, eliminating the +need to recompute expensive calculations or database queries. + +Here's an example code snippet to enable Redis caching in Magento 2: + +```php + [ + 'frontName' => 'admin' + ], + 'cache' => [ + 'frontend' => [ + 'default' => [ + 'backend' => 'Cm_Cache_Backend_Redis', + 'backend_options' => [ + 'server' => 'redis.example.com', + 'port' => '6379' + ] + ], + 'page_cache' => [ + 'backend' => 'Cm_Cache_Backend_Redis', + 'backend_options' => [ + 'server' => 'redis.example.com', + 'port' => '6379' + ] + ] + ] + ] +]; +``` + +## Database Optimization + +Efficient database queries are fundamental for good performance. Here are some techniques to optimize your database +operations: + +### Indexing + +Ensure that your database tables are properly indexed. Indexes can significantly speed up data retrieval operations by +allowing the database engine to quickly locate the required data. Analyze your most frequently executed queries and +identify the columns involved in WHERE or ORDER BY clauses. Then, add indexes on those columns to improve query +performance. + +```sql +CREATE INDEX idx_customer_email ON customer_entity (email); +``` + +### Query Optimization + +Review your SQL queries and optimize them for execution speed. Consider techniques like joining tables instead of using +subqueries, avoiding unnecessary SELECT * statements, and using appropriate WHERE and ORDER BY clauses. + +Example of a poorly optimized query: + +```sql +SELECT * +FROM sales_order +WHERE customer_id IN (SELECT customer_id FROM customer_entity WHERE is_active = 1); +``` + +Optimized version of the above query using JOIN: + +```sql +SELECT so.* +FROM sales_order AS so + INNER JOIN customer_entity AS ce ON so.customer_id = ce.customer_id +WHERE ce.is_active = 1; +``` + +## Code Optimization + +Efficient code is essential for achieving optimal performance. Here are some code optimization techniques for PHP and +Magento 2: + +### Minify CSS and JavaScript + +Minifying your CSS and JavaScript files reduces their file size, resulting in faster download times for your users. +Tools like [CSSMin](https://github.com/tubalmartin/YUI-CSS-compressor-PHP-port) +and [JSMin](https://github.com/mrclay/minify) can help you automatically minify your static assets during the deployment +process. + +### Use Composer Autoloader + +Make sure to utilize the Composer autoloader for efficient class loading. Composer autoloads classes on-demand, reducing +the overhead of loading unnecessary classes. Ensure that the Composer autoloader is configured and optimized in your +project. + +```php +prepare("SELECT * FROM customers WHERE email = ?"); +$stmt->execute([$email]); +``` + +## Caching in Custom Modules + +If you are developing custom modules for Magento 2, make sure to utilize the caching mechanisms provided by the +framework. Utilizing built-in caching can significantly improve the performance of your custom code. You can leverage +the Magento cache types to store the results of expensive operations or frequently accessed data. + +For example, let's assume you have a custom module that fetches a list of products. Instead of querying the database on +every request, you can cache the product data and retrieve it from the cache for subsequent requests. + +```php +cache = $cache; + } + + public function getProductList() + { + $cacheKey = 'product_list'; + $productList = $this->cache->load($cacheKey); + + if (!$productList) { + // Expensive database query to fetch product list here + $productList = $this->fetchProductListFromDatabase(); + + // Store the product list in cache + $this->cache->save($productList, $cacheKey, ['product_list'], 3600); + } + + return $productList; + } +} +``` + +## Conclusion + +By following the performance best practices outlined in this document, you can optimize the speed and efficiency of your +PHP and Magento 2 applications. Remember to utilize caching mechanisms, optimize your database queries, and write +efficient code. Regularly monitor and analyze your application's performance to identify bottlenecks and further +optimize your codebase. diff --git a/performance-testing.md b/performance-testing.md index e69de29..4440bbb 100644 --- a/performance-testing.md +++ b/performance-testing.md @@ -0,0 +1,98 @@ +# Performance Testing Documentation + +[TOC] + +## Introduction + +Performance testing is a critical aspect of software development, as it helps identify and eliminate bottlenecks that +can impact the performance of an application. In this documentation, we will explore the concept of performance testing +and discuss its relevance in the context of PHP and Magento 2. We will also provide instructions on how to conduct +performance testing, along with some best practices and examples. + +## What is Performance Testing? + +Performance testing is a type of software testing that measures the performance, responsiveness, and stability of an +application under specific workload conditions. It helps evaluate the system's ability to handle user interactions, data +processing, and other tasks efficiently. + +## Why is Performance Testing Important in PHP and Magento 2? + +PHP is a popular programming language for building web applications, and Magento 2 is a widely used e-commerce platform +developed in PHP. Both PHP and Magento 2 applications can become complex, with multiple dependencies, plugins, and +customizations. Performance testing becomes crucial in such scenarios to ensure that the application can handle the +expected load and deliver optimal performance to end users. + +### Performance Testing Goals in PHP and Magento 2 + +The primary goals of performance testing in PHP and Magento 2 include: + +1. **Identifying Performance Bottlenecks:** Performance testing helps identify bottlenecks, such as slow database + queries, inefficient code, or resource-intensive operations, that can degrade the application's performance. + +2. **Validating Scalability:** Performance testing ensures that the application can scale effectively with increasing + user load and data volume. It helps determine the system's limits and capacity to handle concurrent requests. + +3. **Optimizing Response Times:** Performance testing helps optimize response times by identifying opportunities for + code or configuration improvements. This leads to a better user experience and increased customer satisfaction. + +## Types of Performance Testing + +There are various types of performance testing that can be conducted. Let's explore a few commonly used ones: + +### Load Testing + +Load testing involves simulating user loads to evaluate the system's behavior under expected or peak workload +conditions. It helps determine whether the application can handle the anticipated user load without performance +degradation. + +Example code snippet for load testing using ApacheBench (ab): + +```bash +ab -n 100 -c 10 http://example.com/ +``` + +### Stress Testing + +Stress testing involves pushing the system beyond its normal operational limits to identify its breaking point. It helps +determine how the system behaves under high-stress conditions and whether it can recover gracefully. + +Example code snippet for stress testing using Siege: + +```bash +siege -c 100 -r 10 http://example.com/ +``` + +### Performance Testing Tools + +There are several performance testing tools available that can help automate the testing process. Some popular ones +include: + +- Apache JMeter +- Gatling +- Locust + +## Best Practices for Performance Testing in PHP and Magento 2 + +To ensure effective performance testing, follow these best practices: + +1. **Define Realistic Workloads:** Create test scenarios that closely resemble real-world usage patterns. Consider + factors like the number of concurrent users, transaction volumes, and data sizes to achieve accurate results. + +2. **Monitor System Resources:** Monitor key system resources, such as CPU usage, memory consumption, and network + metrics, during performance testing. This helps identify resource bottlenecks and potential issues. + +3. **Test with Realistic Data:** Use realistic data for performance testing, including representative product catalogs, + customer profiles, and order volumes. Realistic data helps simulate actual application usage accurately. + +4. **Isolate Performance Testing Environment:** Isolate the performance testing environment from production to prevent + interference or impact on live systems. Use dedicated servers or virtual machines for performance testing activities. + +5. **Test Early and Often:** Incorporate performance testing into the development lifecycle from the early stages. + Regularly test and analyze performance to catch and address performance issues early on. + +## Conclusion + +Performance testing is an essential part of developing high-performance PHP and Magento 2 applications. By following the +best practices and utilizing suitable performance testing tools, you can identify and address potential performance +bottlenecks, optimize response times, and ensure a smooth user experience. Regular performance testing is key to +maintaining and improving the overall performance of your application. diff --git a/plugins.md b/plugins.md index e69de29..a2821b6 100644 --- a/plugins.md +++ b/plugins.md @@ -0,0 +1,121 @@ +# Plugin Documentation + +[TOC] + +## Introduction + +Plugins in Magento 2 provide a way to extend and modify the behavior of existing code without directly modifying it. +This allows developers to customize Magento 2's functionality without the need for modifying core files, ensuring easier +upgrades and compatibility with other extensions. In this documentation, we will explore the concept of plugins, their +usage, and provide practical examples for better understanding. + +## Plugin Basics + +A plugin, also known as an interceptor, is a class that modifies the behavior of a public method in a target class. It +allows you to execute custom code before, after, or around the execution of the original method, without modifying the +original code directly. This can be useful for adding new functionality, logging, caching, or modifying the input/output +of a method. + +## Plugin Types + +There are three types of plugins that can be used in Magento 2: `before`, `after`, and `around`. Let's discuss each type +in more detail. + +### 1. Before Plugin + +A `before` plugin allows you to execute custom code before the execution of the target method. This is useful for +intercepting the input parameters and modifying them if needed. For example, let's say we have a +method `doSomething($param1, $param2)` in a class `TargetClass`. We can create a `before` plugin to intercept the +execution of this method and modify the input parameters: + +```php +class BeforePlugin +{ + public function beforeDoSomething($subject, $param1, $param2) + { + // Modify $param1 and $param2 here + $param1 = 'Modified ' . $param1; + $param2 += 10; + + // You can also modify the subject instance itself if needed + $subject->setSomeProperty('Modified Value'); + + // Always return the modified parameters + return [$param1, $param2]; + } +} +``` + +### 2. After Plugin + +An `after` plugin allows you to execute custom code after the execution of the target method. This is useful for +intercepting the return value of the method and modifying it if needed. For example, let's say we have a +method `doSomething()` in a class `TargetClass` that returns a value. We can create an `after` plugin to intercept the +execution of this method and modify the return value: + +```php +class AfterPlugin +{ + public function afterDoSomething($subject, $result) + { + // Modify $result here + $result = 'Modified ' . $result; + + // Return the modified result + return $result; + } +} +``` + +### 3. Around Plugin + +An `around` plugin allows you to execute custom code before and/or after the execution of the target method. This is +useful when you want to completely override the original method's behavior or conditionally execute custom code. For +example, let's say we have a method `doSomething()` in a class `TargetClass`. We can create an `around` plugin to +intercept the execution of this method and modify its behavior: + +```php +class AroundPlugin +{ + public function aroundDoSomething($subject, $proceed) + { + // Code to execute before the original method + + // Call the original method using $proceed() + $result = $proceed(); + + // Code to execute after the original method + + // Modify $result if needed + + // Return the modified result + return $result; + } +} +``` + +## Plugin Configuration + +To use a plugin in Magento 2, you need to define its configuration in your module's `di.xml` file. Here's an example of +how to configure a plugin for a class `TargetClass`: + +```xml + + + + + + + + +``` + +Make sure to replace `TargetClass`, `Vendor\Module`, and plugin names with your actual class and module names. + +## Conclusion + +Plugins are a powerful tool in Magento 2 that allows you to modify the behavior of existing code without directly +modifying it. By leveraging the `before`, `after`, and `around` plugin types, you can customize Magento's functionality +to meet your specific requirements. Remember to configure your plugins in the `di.xml` file of your module. Happy plugin +development! diff --git a/recommended-development-workflows.md b/recommended-development-workflows.md index e69de29..8b7d25d 100644 --- a/recommended-development-workflows.md +++ b/recommended-development-workflows.md @@ -0,0 +1,128 @@ +# Recommended Development Workflows + +[TOC] + +This documentation provides recommendations for development workflows when working with PHP and Magento 2. Following +these workflows will help developers maintain a structured and efficient approach to building and maintaining Magento 2 +projects. This document assumes a basic understanding of PHP, Magento 2, and the command line interface (CLI). + +## Local Development Environment + +To start with, it is essential to have a local development environment set up. This ensures that developers have a +consistent and isolated environment for building and testing Magento 2 projects. Here are the recommended tools and +configurations: + +- **PHP**: Install the latest version of PHP (compatible with Magento 2) and configure it with commonly used extensions. +- **Composer**: Install Composer, the dependency management tool for PHP. Composer simplifies the installation and + management of Magento 2 and third-party extensions. +- **Web Server**: Set up a web server (e.g., Apache or Nginx) and configure it to serve Magento 2 projects. +- **Database**: Install and configure a MySQL database server, which is the recommended database engine for Magento 2. +- **Magento 2**: Install a clean instance of Magento 2 using Composer or the command-line interface. + +## Version Control + +Version control is crucial for tracking changes, collaborating with other developers, and ensuring code integrity. Git +is the recommended version control system for Magento 2 projects. Here are the main aspects to consider: + +- **Repository Structure**: Create a repository at the root of your Magento 2 project. Add the necessary configuration + files to exclude irrelevant files from version control (e.g., `vendor/` directory, environment-specific + configurations). +- **Ignored Files**: Create a `.gitignore` file to exclude files and directories that should not be versioned. This file + should include common Magento 2 files and directories that are not required in a development workflow. +- **Branches**: Use branches to separate different development tasks or features. Create a new branch for each task and + merge it back into the main branch (usually `master` or `develop`) once completed. This approach ensures that the main + branch always contains stable and tested code. +- **Commit Messages**: Provide meaningful and concise commit messages that describe the changes made in each commit. Use + imperative verbs to indicate the purpose of the commit (e.g., "Add feature X," "Fix issue Y"). +- **Tags**: Use tags to mark important milestones or releases in your project. This makes it easier to track and + reference specific versions of your codebase. + +## Branching Strategy + +Having a well-defined branching strategy helps streamline the development process and enables collaboration between team +members. The following branching model, known as Gitflow, is recommended: + +- **Master Branch**: The `master` branch should always contain stable and production-ready code. Never commit directly + to this branch; instead, use it to represent the latest release version. +- **Develop Branch**: The `develop` branch acts as the main integration branch for new features and bug fixes. + Developers should create feature branches from this branch and merge their changes back into it. This branch should + ideally always be deployable and tested. +- **Feature Branches**: Developers create feature branches from the `develop` branch when working on new features or + significant changes. Once completed, these branches are merged back into the `develop` branch. +- **Release Branches**: When preparing for a new release, create a release branch from the `develop` branch. This branch + allows for last-minute bug fixes and fine-tuning before the release. Once the release is ready, merge the release + branch back into both the `develop` and `master` branches. +- **Hotfix Branches**: Hotfix branches are created from the `master` branch to fix critical issues in a live production + environment. Once fixed, the hotfix branch should be merged into both the `develop` and `master` branches. + +## Coding Standards + +Consistent coding standards help maintain code readability and improve collaboration among developers. For Magento 2 +projects, it is recommended to follow the Magento Coding Standard (MCS), which is based on the PSR-2 standard with +additional Magento-specific rules. Here's how you can enforce coding standards: + +- **Code Sniffer**: Use PHP_CodeSniffer with the Magento 2 coding standard installed to automatically check your code + for compliance. You can run the code sniffer from the command line or integrate it with your development environment. +- **IDE Integration**: Configure your IDE (e.g., PhpStorm, Visual Studio Code) to automatically format your code + according to the coding standard. This ensures that your code is consistently formatted as you write it. +- **Pre-commit Hooks**: Set up pre-commit hooks to check and reject commits that violate the coding standard. This + prevents non-compliant code from being committed to the repository. + +## Code Review + +Code review is an essential part of the development process, helping identify bugs, improve code quality, and facilitate +knowledge sharing. Here are some recommended practices for effective code reviews: + +- **Pull Requests**: Use pull requests or merge requests to initiate code reviews. These mechanisms provide a + transparent and collaborative way to review and discuss proposed changes. +- **Reviewers**: Assign reviewers who are knowledgeable in the relevant areas of the codebase. Having multiple reviewers + ensures a thorough review and minimizes the chance of overlooking potential issues. +- **Structured Reviews**: Establish a checklist or guidelines for reviewers to follow during code reviews. This ensures + consistency and helps reviewers focus on specific aspects of the code (e.g., functionality, performance, security). +- **Constructive Feedback**: Provide constructive feedback that helps the developer understand the reasoning behind + suggested changes. Focus on improving the code rather than criticizing the developer. +- **Automated Tools**: Utilize automated tools (e.g., static analysis, security scanners) to supplement code reviews and + identify potential issues that may have been missed. + +## Continuous Integration + +Continuous Integration (CI) is a practice that automates the process of building, testing, and deploying code changes. +CI helps catch issues early and ensures that the codebase is always in a deployable state. Here's how to set up a CI +pipeline for Magento 2 projects: + +- **Build Environment**: Configure a build environment that closely resembles the production environment. This includes + installing the necessary dependencies and configuring the web server and database. +- **Build Scripts**: Create build scripts (e.g., bash scripts, CI configuration files) that automate the build, test, + and deployment processes. These scripts should be versioned and executed by the CI server. +- **Automated Tests**: Write automated tests (e.g., unit tests, integration tests) that cover critical parts of the + codebase. These tests should be executed as part of the CI pipeline to ensure code quality and prevent regressions. +- **Static Analysis**: Integrate static analysis tools (e.g., PHPStan, SonarQube) into the CI pipeline to catch code + issues and enforce coding standards. +- **Deployment**: Automate the deployment process as much as possible. Use tools like Capistrano, Deployer, or custom + scripts to deploy the code to staging or production environments. Ensure that deployments are reversible and have + proper rollback mechanisms. + +## Deployment + +Deploying Magento 2 projects requires careful consideration to ensure a smooth transition from development to +production. Here are some recommended best practices for deployment: + +- **Environment Configuration**: Maintain separate configuration files for each environment (e.g., development, staging, + production). These files should contain environment-specific settings such as database credentials and cache + configurations. +- **Dependency Management**: Ensure that all dependencies are correctly installed on the production environment. Use + Composer to manage and install both Magento 2 and third-party extensions. +- **Compilation and Cache**: Compile and deploy static assets (e.g., JavaScript, CSS) to minimize server-side processing + and improve frontend performance. Clear the cache after deployment to ensure that the latest changes are reflected. +- **Database Migration**: Use Magento 2's built-in database migration tools ( + e.g., `setup:upgrade`, `setup:db-schema:upgrade`) to update the database schema and data. These tools handle + versioning and ensure that the database is in sync with the codebase. +- **Monitoring**: Set up monitoring tools (e.g., New Relic, Nagios) to track the health and performance of your Magento + 2 application. Monitoring provides insights into potential issues and helps you proactively address them. + +## Conclusion + +Following these recommended development workflows will help ensure a structured, efficient, and collaborative +development process for Magento 2 projects. By setting up a local development environment, implementing version control, +enforcing coding standards, performing code reviews, integrating continuous integration, and following best practices +for deployment, developers can build and maintain high-quality Magento 2 applications. diff --git a/reporting-security-issues.md b/reporting-security-issues.md index e69de29..5134052 100644 --- a/reporting-security-issues.md +++ b/reporting-security-issues.md @@ -0,0 +1,80 @@ +# Reporting Security Issues + +[TOC] + +Thank you for your interest in improving the security of PHP and Magento 2. We highly appreciate your efforts in +reporting any security vulnerabilities you may come across. Your contribution helps us ensure the safety and integrity +of our software. + +## Security Vulnerabilities + +A security vulnerability refers to a weakness or flaw in software that can be exploited by attackers to compromise the +system's confidentiality, integrity, or availability. Examples of security vulnerabilities could include cross-site +scripting (XSS), SQL injection, remote code execution, or insecure direct object references. + +## Responsible Disclosure + +We strongly encourage responsible disclosure of any security vulnerabilities you discover. This means that you should +not publicly disclose the details of a vulnerability until it has been resolved. Instead, we kindly ask you to report +the issue directly to us so that we can investigate and take necessary actions to protect our users. + +## Reporting Process + +To report a security issue, please follow these steps: + +1. **Gather Information**: Collect as much information as possible about the vulnerability you have discovered. Include + a detailed description of the issue, along with any steps or code snippets needed to reproduce it. This information + will help us understand and address the problem more efficiently. + +2. **Contact Us**: Send an email to our dedicated security team at security@example.com. Include the subject line " + Security Vulnerability Report" to ensure prompt attention. In your email, provide a clear and concise explanation of + the vulnerability, including any relevant supporting materials or code samples. + +3. **Encryption**: Please encrypt your email using our [PGP key](https://example.com/security/pgp-key.asc) to protect + the confidentiality of the information you are sharing. This step ensures that only authorized recipients can access + the contents of your report. + +4. **Response**: Our security team will acknowledge receipt of your report within 24 hours. We will then begin + investigating the issue and keeping you informed about our progress. Once we have resolved the vulnerability, we will + notify you and provide credit for your responsible disclosure if desired. + +## Vulnerability Examples + +Here are a couple of examples to illustrate what we consider a well-written vulnerability report. + +### Example 1: Cross-Site Scripting (XSS) + +**Description**: A persistent cross-site scripting vulnerability was discovered in the `customer_name` field of the +checkout form. By injecting malicious JavaScript code, an attacker could execute arbitrary code in the context of the +victim's browser. + +**Steps to Reproduce**: + +1. Log in as a customer with the role of "registered user." +2. Add an item to your cart and proceed to the checkout page. +3. In the `customer_name` field, enter the following payload: `` +4. Complete the checkout process and observe that the payload is executed when viewing the order details. + +**Impact**: This vulnerability allows an attacker to execute arbitrary code on the victim's browser, potentially leading +to session hijacking, data theft, or unauthorized actions on the affected website. + +### Example 2: SQL Injection + +**Description**: A time-based blind SQL injection vulnerability was identified in the `getProductById()` function of +the `ProductRepository` class. By manipulating the `productId` parameter, an attacker can extract sensitive information +from the database. + +**Steps to Reproduce**: + +1. Retrieve the product details by calling the `getProductById()` function with the following + payload: `1 OR SLEEP(5) --` +2. Observe that the response is delayed by approximately 5 seconds, indicating a successful time-based injection. + +**Impact**: Successful exploitation of this vulnerability allows an attacker to retrieve sensitive information from the +database, such as customer records, order details, or other confidential data. + +## Conclusion + +We appreciate your commitment to improving the security of PHP and Magento 2. By responsibly disclosing any +vulnerabilities you discover, you contribute to the ongoing protection of our users and maintain the integrity of our +software. Thank you for your cooperation, and we look forward to working with you to address any security concerns. diff --git a/requirejs.md b/requirejs.md index e69de29..4ce49c5 100644 --- a/requirejs.md +++ b/requirejs.md @@ -0,0 +1,178 @@ +# RequireJS Documentation + +[TOC] + +## Introduction + +RequireJS is a JavaScript file and module loader that improves the efficiency and organization of code in web +applications. It allows you to break your code into small, modular pieces called modules and load them only when they +are needed, reducing the initial download time of your web page and improving the overall performance of your +application. + +This documentation will provide a comprehensive guide to using RequireJS with a focus on integrating it with PHP and +Magento 2. We will cover the basic concepts of RequireJS, its configuration, and how to use it effectively in a Magento +2 environment. + +## Installation + +To get started with RequireJS, you can download it from the official website or include it via a package manager like +npm or Yarn. For Magento 2, RequireJS is already packaged and included in the installation. + +You can include RequireJS in your HTML file by adding the following script tag: + +```html + + +``` + +## Basic Concepts + +### Modules + +Modules are the building blocks of RequireJS. They encapsulate a piece of code, usually in a separate file, and expose +specific functionalities or data through a defined interface. + +A module can be defined using the `define` function provided by RequireJS. It takes an array of dependencies and a +callback function that returns the module's exports. + +```javascript +define(['dependency1', 'dependency2'], function (dep1, dep2) { + // Module code here + return { + // Exports of the module + }; +}); +``` + +### Dependencies + +Dependencies are other modules that are required by a module to function correctly. RequireJS ensures that all +dependencies are loaded before executing the module code. + +Dependencies are specified as an array of module names in the `define` function. The order of the dependencies is +important if the modules rely on each other. + +```javascript +define(['dependency1', 'dependency2'], function (dep1, dep2) { + // Module code here +}); +``` + +### Asynchronous Module Definition (AMD) + +RequireJS uses the Asynchronous Module Definition (AMD) format. This means that modules are loaded and executed +asynchronously, improving the performance of web applications. + +AMD allows you to load modules on-demand, reducing the initial loading time of your application. It also provides a +clean and modular way to organize your code, making it easier to maintain and refactor. + +## Configuring RequireJS + +### RequireJS Configuration Object + +RequireJS provides a configuration object that allows you to customize its behavior. You can specify module paths, shims +for non-AMD modules, and various other options. + +The configuration object can be set using the `requirejs.config` method. It takes an object with configuration options +as its parameter. + +```javascript +requirejs.config({ + // Configuration options here +}); +``` + +### Configuration Example + +Here's an example of how to configure RequireJS with custom module paths and shims: + +```javascript +requirejs.config({ + baseUrl: 'js', + paths: { + 'jquery': 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min', + 'lodash': 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min', + }, + shim: { + 'jquery': { + exports: '$' + }, + 'lodash': { + exports: '_' + } + } +}); +``` + +In this example, we set the base URL for all module paths to `'js'`, so RequireJS will look for modules in the `js` +directory. We also specify the paths for the `jquery` and `lodash` modules using CDN URLs. + +The `shim` option is used to define exports for non-AMD modules. In this case, we specify that the `jquery` module +exports the global variable `$`, and the `lodash` module exports the global variable `_`. + +## Using RequireJS in Magento 2 + +### Adding JavaScript Dependencies + +Magento 2 uses RequireJS to manage JavaScript dependencies. To add new JavaScript dependencies to your Magento 2 module +or theme, you need to create a `requirejs-config.js` file. + +In the `requirejs-config.js` file, you can specify the module name, its dependencies, and any other configuration +options. + +Here's an example of how to add a JavaScript dependency to a Magento 2 theme: + +```javascript +var config = { + paths: { + 'my-custom-script': 'Vendor_Module/js/custom-script' + } +}; +``` + +In this example, we define a new module called `'my-custom-script'` and specify its path +as `'Vendor_Module/js/custom-script'`. This means that the module file `custom-script.js` should be located in +the `Vendor/Module/view/frontend/web/js` directory. + +### Defining Custom Modules + +To define custom modules in Magento 2, you can use the AMD format provided by RequireJS. Create a new JavaScript file +for your module and define it using the `define` function. + +Here's an example of how to define a custom module in Magento 2: + +```javascript +define(['jquery', 'lodash'], function ($, _) { + // Module code here +}); +``` + +In this example, we define a custom module that has `jquery` and `lodash` as dependencies. The module code can use +the `$` and `_` variables to access the functionality provided by jQuery and Lodash. + +### Using RequireJS in Custom Magento 2 Themes + +To load and use modules in a custom Magento 2 theme, you can use the `data-mage-init` attribute in HTML tags. This +attribute allows you to specify the module and its configuration options. + +Here's an example of how to use RequireJS in a custom Magento 2 theme: + +```html + +
+ +
+``` + +In this example, we use the `data-mage-init` attribute to initialize the `'my-custom-script'` module with the specified +configuration options. The module code will be executed for the specified HTML element. + +## Conclusion + +RequireJS is a powerful tool that enhances the performance and organization of JavaScript code in web applications. By +breaking code into modules and loading them asynchronously, you can improve the loading time of your web page and create +a more maintainable codebase. + +In this documentation, we covered the basic concepts of RequireJS, its configuration options, and how to use it +effectively in a Magento 2 environment. By following the guidelines and examples provided, you should be able to +leverage RequireJS to enhance your PHP and Magento 2 projects. diff --git a/rest-apis-soap-apis.md b/rest-apis-soap-apis.md index e69de29..552b6ee 100644 --- a/rest-apis-soap-apis.md +++ b/rest-apis-soap-apis.md @@ -0,0 +1,136 @@ +# REST APIs and SOAP APIs Documentation + +[TOC] + +## Introduction + +This documentation provides an overview of REST APIs and SOAP APIs, their differences, and how to use them in the +context of PHP and Magento 2. Both REST and SOAP APIs are widely used in web development to facilitate communication +between different systems or applications. + +## REST APIs + +REST (Representational State Transfer) APIs are a popular architectural style for building web services. They utilize +the HTTP protocol and its methods (GET, POST, PUT, DELETE) to perform operations on resources. REST APIs are +lightweight, simple, and easier to understand and implement compared to SOAP. + +### Using REST APIs in PHP and Magento 2 + +In PHP and Magento 2, you can use built-in libraries and frameworks, such as Guzzle, to work with REST APIs. Here's an +example of how to make a GET request to a REST API endpoint using Guzzle: + +```php +use GuzzleHttp\Client; + +$client = new Client(); +$response = $client->get('https://api.example.com/users'); + +$body = $response->getBody(); +$data = json_decode($body, true); +``` + +In the above code snippet, we create a `Client` instance from Guzzle and make a GET request to retrieve a list of users +from the API endpoint `https://api.example.com/users`. The response is then parsed as JSON and stored in the `$data` +variable. + +### Example REST API Endpoint: Get User Information + +To illustrate how to work with REST APIs further, let's consider an example endpoint that retrieves user information. + +**Endpoint:** `/api/users/{id}` + +**Method:** GET + +**Parameters:** + +- `id` (required): The ID of the user to retrieve information for. + +**Response:** + +```json +{ + "id": 123, + "name": "John Doe", + "email": "john.doe@example.com" +} +``` + +To retrieve user information using this REST API endpoint in PHP and Magento 2, you can modify the previous code snippet +as follows: + +```php +$id = 123; +$response = $client->get('https://api.example.com/users/' . $id); +$body = $response->getBody(); +$data = json_decode($body, true); + +$userName = $data['name']; +$userEmail = $data['email']; +``` + +In the above code, we specify the user ID (123) and concatenate it with the API endpoint URL to retrieve information for +a specific user. + +## SOAP APIs + +SOAP (Simple Object Access Protocol) APIs are another way to build web services. They use XML to define their message +structure and typically operate over HTTP or other protocols. SOAP APIs are more complex and can offer advanced features +such as built-in error handling and security. + +### Using SOAP APIs in PHP and Magento 2 + +To work with SOAP APIs in PHP and Magento 2, you can utilize the built-in `SoapClient` class. Here's an example of how +to call a SOAP API method: + +```php +$wsdl = 'https://api.example.com/soap?wsdl'; +$soapClient = new SoapClient($wsdl); + +$response = $soapClient->getUserInfo(['id' => 123]); +$userInfo = $response->getUserInfoResult; +``` + +In the above code snippet, we create a `SoapClient` instance by providing the URL to the WSDL (Web Services Description +Language) file of the SOAP API. We then call the `getUserInfo` method, passing the required parameters as an associative +array. The response is stored in the `$userInfo` variable. + +### Example SOAP API Method: Get User Information + +Let's consider an example SOAP API method that retrieves user information. + +**Method:** `getUserInfo` + +**Parameters:** + +- `id` (required): The ID of the user to retrieve information for. + +**Response:** + +```xml + + + + 123 + John Doe + john.doe@example.com + + +``` + +To call the `getUserInfo` SOAP API method in PHP and Magento 2, you can modify the previous code snippet as follows: + +```php +$response = $soapClient->getUserInfo(['id' => 123]); +$userName = $response->getUserInfoResult->name; +$userEmail = $response->getUserInfoResult->email; +``` + +In the above code, we call the `getUserInfo` method, passing the user ID (123) as a parameter. The response is then +accessed using object notation to extract the user's name and email. + +## Conclusion + +In this documentation, we discussed the basics of REST APIs and SOAP APIs, their usage in PHP and Magento 2, and +provided examples of how to work with them. REST APIs are simpler and commonly used, while SOAP APIs offer advanced +features but have more complexity. By understanding these concepts and examples, you can effectively interact with REST +and SOAP APIs in your PHP and Magento 2 projects. diff --git a/rest-apis.md b/rest-apis.md index e69de29..69de51c 100644 --- a/rest-apis.md +++ b/rest-apis.md @@ -0,0 +1,207 @@ +# REST APIs Documentation + +[TOC] + +This documentation provides a comprehensive guide to using REST APIs in PHP and Magento 2. REST (Representational State +Transfer) APIs are a set of rules and conventions that enable communication between different software applications over +the internet. In this guide, we will cover the basics of REST APIs, how to make requests, handle responses, and provide +practical examples using PHP and Magento 2. + +## 1. Introduction to REST APIs + +REST APIs follow a client-server architecture, where the client (your application) makes requests to a server (the API) +to perform certain actions or retrieve information. REST APIs use standard HTTP methods such as GET, POST, PUT, and +DELETE to manipulate resources. + +REST APIs in Magento 2 are organized around specific concepts, such as products, customers, orders, and categories. Each +of these concepts is represented by a resource, which can be accessed by a unique URL. For example, to retrieve +information about a product, you would make a GET request to the `/products/{productId}` endpoint. + +## 2. Making API Requests + +To make requests to REST APIs in PHP, you can use the cURL library, which provides a flexible and powerful set of +functions for making HTTP requests. + +Here's an example of making a GET request to retrieve product information: + +```php +$ch = curl_init(); +curl_setopt($ch, CURLOPT_URL, 'https://example.com/rest/V1/products/123'); +curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); +$response = curl_exec($ch); +curl_close($ch); + +// Process the response +if ($response) { + $product = json_decode($response, true); + // Handle the product data +} else { + // Handle the error +} +``` + +In this example, we initialize a cURL handle (`$ch`), set the URL of the API endpoint, and enable +the `CURLOPT_RETURNTRANSFER` option to receive the response as a string. We then execute the request using `curl_exec()` +and close the cURL handle. + +## 3. Handling API Responses + +API responses typically come in the form of JSON (JavaScript Object Notation), which is a lightweight data interchange +format. JSON data can be easily parsed and manipulated using PHP's `json_decode()` function. + +Here's an example of handling a response from the previous GET request: + +```php +if ($response) { + $product = json_decode($response, true); + if ($product) { + // Access specific product attributes + $sku = $product['sku']; + $name = $product['name']; + $price = $product['price']; + // Handle the retrieved product data + } else { + // Handle JSON decoding error + } +} else { + // Handle the error +} +``` + +In this example, we check if the response is not empty, then decode the JSON response into an associative array +using `json_decode()` with the `true` option. We can then access specific attributes of the product and perform the +necessary operations. + +## 4. Authentication and Authorization + +Magento 2 REST APIs require authentication and authorization to ensure secure access to resources. To authenticate, you +need to obtain an access token by sending a POST request with your credentials to the `/integration/admin/token` +endpoint. + +Here's an example of obtaining an access token: + +```php +$ch = curl_init(); +curl_setopt($ch, CURLOPT_URL, 'https://example.com/rest/V1/integration/admin/token'); +curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); +curl_setopt($ch, CURLOPT_POST, true); +curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([ + 'username' => 'admin', + 'password' => 'admin123' +])); +$response = curl_exec($ch); +curl_close($ch); + +if ($response) { + $token = json_decode($response, true); + // Use the token for subsequent API requests +} else { + // Handle the error +} +``` + +In this example, we send a POST request to the `/integration/admin/token` endpoint with the `username` and `password` as +JSON-encoded data in the request body. We then retrieve the access token from the response and use it for subsequent API +requests. + +## 5. Practical Examples in PHP and Magento 2 + +To illustrate the usage of REST APIs in PHP and Magento 2, let's consider some practical examples. + +### Example 1: Creating a New Product + +To create a new product using the Magento 2 API, you would make a POST request to the `/products` endpoint with the +product data in the request body. + +```php +$ch = curl_init(); +curl_setopt($ch, CURLOPT_URL, 'https://example.com/rest/V1/products'); +curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); +curl_setopt($ch, CURLOPT_POST, true); +curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([ + 'sku' => 'new-product', + 'name' => 'New Product', + 'price' => 9.99, + // Additional product data +])); +curl_setopt($ch, CURLOPT_HTTPHEADER, [ + 'Authorization: Bearer ' . $token, + 'Content-Type: application/json' +]); +$response = curl_exec($ch); +curl_close($ch); + +if ($response) { + // Handle the success response +} else { + // Handle the error +} +``` + +In this example, we send a POST request to the `/products` endpoint with the product data included in the request body. +We also set the appropriate headers, including the access token obtained through authentication. + +### Example 2: Retrieving Order Details + +To retrieve details of a specific order using the Magento 2 API, you would make a GET request to the `/orders/{orderId}` +endpoint. + +```php +$ch = curl_init(); +curl_setopt($ch, CURLOPT_URL, 'https://example.com/rest/V1/orders/123'); +curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); +curl_setopt($ch, CURLOPT_HTTPHEADER, [ + 'Authorization: Bearer ' . $token +]); +$response = curl_exec($ch); +curl_close($ch); + +if ($response) { + $order = json_decode($response, true); + // Handle the retrieved order details +} else { + // Handle the error +} +``` + +In this example, we send a GET request to the `/orders/{orderId}` endpoint, including the order ID in the URL. We also +include the access token in the request header for authentication. + +### Example 3: Updating Customer Information + +To update a customer's information using the Magento 2 API, you would make a PUT request to +the `/customers/{customerId}` endpoint with the updated data in the request body. + +```php +$ch = curl_init(); +curl_setopt($ch, CURLOPT_URL, 'https://example.com/rest/V1/customers/123'); +curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); +curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); +curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([ + 'firstname' => 'John', + 'lastname' => 'Doe', + // Additional customer data to update +])); +curl_setopt($ch, CURLOPT_HTTPHEADER, [ + 'Authorization: Bearer ' . $token, + 'Content-Type: application/json' +]); +$response = curl_exec($ch); +curl_close($ch); + +if ($response) { + // Handle the success response +} else { + // Handle the error +} +``` + +In this example, we send a PUT request to the `/customers/{customerId}` endpoint with the updated customer data in the +request body. We also set the appropriate headers, including the access token obtained through authentication. + +## Conclusion + +This documentation provided an overview of REST APIs, explained how to make requests, handle responses, and covered +authentication and authorization in PHP and Magento 2. We also provided practical examples to illustrate the concepts +discussed. With this knowledge, you should be able to confidently interact with REST APIs in your PHP and Magento 2 +projects and leverage the power of remote resource manipulation. diff --git a/routes-xml.md b/routes-xml.md deleted file mode 100644 index e69de29..0000000 diff --git a/routes_xml.md b/routes_xml.md new file mode 100644 index 0000000..b2dfc20 --- /dev/null +++ b/routes_xml.md @@ -0,0 +1,96 @@ +# `routes.xml` Reference Documentation + +[TOC] + +## Introduction + +The `routes.xml` file is an essential configuration file in Magento 2, particularly when it comes to defining and +managing custom routes. This file plays a crucial role in routing HTTP requests to the appropriate controllers in your +Magento 2 module. In this document, you will learn how to effectively utilize the `routes.xml` file to create and manage +routes in your Magento 2 module. + +## File Location and Structure + +The `routes.xml` file resides in the `etc/frontend` or `etc/adminhtml` directory of your module. The exact file path +depends on whether your module is for the frontend or admin area of Magento 2. The file follows a structured XML format +and consists of multiple elements that define the routes and their associated controllers. + +Here is an example of the basic structure of a `routes.xml` file: + +```xml + + + + + + + + +``` + +Let's dive into each of these elements to gain a deeper understanding. + +## `` Element + +The `` element is the root element of the `routes.xml` file. It defines the XML namespace and specifies the +schema location using the `xmlns:xsi` and `xsi:noNamespaceSchemaLocation` attributes, respectively. You don't need to +modify these attributes as they refer to the default schema provided by Magento. + +## `` Element + +The `` element is used to define the router ID, which is a unique identifier for the router. The router ID is +used to group related routes together. In most cases, you will use either `standard` or `admin` as the router ID. For +example, `` defines a router for the frontend area, whereas `` defines a router +for the admin area. + +## `` Element + +The `` element represents a specific route in Magento 2. It consists of three attributes: `id`, `frontName`, and +optional `disabled`. + +- The `id` attribute specifies a unique identifier for the route and is used internally by Magento to identify and match + the incoming requests. +- The `frontName` attribute defines the URL segment that precedes the action name in the URL. For example, + if `frontName="custom"`, the URL `https://example.com/custom/index/index` will map to the `Index/Index` action of the + associated controller. +- The optional `disabled` attribute, when set to `true`, disables the route. This can be useful when you want to + temporarily deactivate a route without removing it from the `routes.xml` file. + +## `` Element + +The `` element is a child element of the `` element, and it specifies the name of the module that handles +the route. The `name` attribute should match the module's name as defined in its `module.xml` file. + +## Example + +Let's walk through an example to illustrate how the `routes.xml` file works. Assume we have a module +named `Acme_CustomModule` that needs to define a custom route for frontend pages. + +Here is the `routes.xml` file for this module: + +```xml + + + + + + + + +``` + +In this example, we defined a route with the `id` of "custom" and `frontName` of "custom". The associated module is +specified as `Acme_CustomModule`. + +Now, let's assume we have a controller named `Index` inside the `Acme\CustomModule\Controller\Index` namespace. With +this `routes.xml` configuration, the URL `https://example.com/custom/index/index` will map to the `Index` +controller's `index` action. + +## Conclusion + +The `routes.xml` file is a crucial component for defining and managing routes in Magento 2. By carefully configuring +this file, you can easily map incoming HTTP requests to the appropriate controllers within your module. Understanding +the structure and elements of the `routes.xml` file will empower you to create custom routes efficiently. Remember to +adhere to the XML structure and use correct attribute values to ensure proper routing functionality. diff --git a/scalability-options-and-recommendations.md b/scalability-options-and-recommendations.md index e69de29..5253da9 100644 --- a/scalability-options-and-recommendations.md +++ b/scalability-options-and-recommendations.md @@ -0,0 +1,110 @@ +# Scalability Options and Recommendations + +[TOC] + +## Introduction + +Scalability is a crucial aspect of any software application. As your PHP-based Magento 2 store grows, it's essential to +ensure that your architecture can handle increasing traffic and maintain optimal performance. In this guide, we will +discuss various scalability options and provide recommendations to help you scale your Magento 2 store effectively. + +## Caching + +Caching plays a vital role in improving the performance of your Magento 2 store. By storing frequently accessed data in +cache, you can reduce the load on your database and improve response times. Magento 2 provides built-in caching +mechanisms that you can leverage: + +### Full Page Cache (FPC) + +Magento 2 comes with a powerful Full Page Cache (FPC) system that caches entire pages and delivers them to users without +executing PHP code or accessing the database. Enabling FPC can significantly improve the performance of your store, +especially for static or semi-static pages. + +To enable FPC in Magento 2, navigate to the **Stores** > **Configuration** > **Advanced** > **System** > **Full Page +Cache** section in the Magento admin panel. Choose the caching mechanism that suits your environment, such as Redis or +Varnish, and configure it accordingly. + +### Object Caching + +In addition to FPC, Magento 2 provides an object caching mechanism that allows you to cache specific data objects. By +caching objects, you can reduce the time spent on expensive operations, such as database queries or API calls. + +Magento 2 supports various caching backends, including Redis, Memcached, and the built-in file-based cache. To configure +object caching, navigate to the **Stores** > **Configuration** > **Advanced** > **System** > **Cache Management** +section in the Magento admin panel. + +## Load Balancing + +As your store's traffic grows, a single server might not be able to handle the load efficiently. Load balancing +distributes incoming requests across multiple servers, allowing you to scale horizontally and improve performance. Here +are a couple of load balancing options you can consider: + +### Nginx Load Balancer + +Nginx is a popular web server that can also act as a load balancer. By configuring an Nginx load balancer, you can +distribute traffic among multiple backend web servers running your Magento 2 application. + +Here's an example configuration snippet for an Nginx load balancer: + +```nginx +http { + upstream backend { + server magento-server1; + server magento-server2; + # Add more backend servers as needed + } + + server { + listen 80; + server_name your-store.com; + + location / { + proxy_pass http://backend; + } + } +} +``` + +### Elastic Load Balancer (ELB) + +If you are hosting your Magento 2 store on a cloud provider like AWS, you can utilize their Elastic Load Balancer (ELB) +service. ELB automatically spreads incoming traffic across multiple instances, providing both scalability and high +availability. + +To configure ELB for your Magento 2 store, refer to the documentation of your cloud provider. + +## Database Scaling + +The database is often a bottleneck when it comes to handling large amounts of data or high levels of concurrent +requests. Here are a few strategies to scale your Magento 2 database: + +### Master-Slave Replication + +Master-Slave replication involves creating multiple database instances, with one designated as the master and others as +read-only slaves. The master handles write operations, while the slaves replicate data from the master and handle read +operations. + +To configure Magento 2 to use a database replica, you need to update the `env.php` configuration file with the +appropriate database credentials for each replica. + +### Sharding + +Sharding involves dividing your database into smaller, independent parts called shards. Each shard consists of a subset +of your data, allowing for parallel processing and improved performance. Magento 2 doesn't provide built-in sharding +functionality, but you can implement it manually by modifying your application code and database schema. + +## Content Delivery Network (CDN) + +A Content Delivery Network (CDN) can significantly improve the performance and scalability of your Magento 2 store by +caching and delivering static content from edge servers located worldwide. By offloading static asset delivery to a CDN, +you reduce the load on your web servers and improve response times for users across the globe. + +Magento 2 supports integration with popular CDNs such as Cloudflare, Fastly, and Akamai. Consult the documentation of +your chosen CDN for specific instructions on integrating it with Magento 2. + +## Conclusion + +Scaling your Magento 2 store is a critical step towards ensuring optimal performance and handling increasing traffic. By +leveraging caching mechanisms, load balancing, database scaling strategies, and CDNs, you can effectively scale your +store to meet growing demands. Be sure to monitor your system's performance and make adjustments as needed to ensure +your store continues to provide a seamless shopping experience for your customers. diff --git a/search.md b/search.md index e69de29..0cf8e9c 100644 --- a/search.md +++ b/search.md @@ -0,0 +1,131 @@ +# Search Documentation + +[TOC] + +## Introduction + +This documentation provides a comprehensive guide to implementing and optimizing search functionality in a PHP-based +e-commerce platform, specifically Magento 2. It covers the key concepts, techniques, and best practices for search +implementation and customization. By following this guide, you will be able to enhance the search experience for your +users and improve the overall performance of your application. + +## 1. Search Basics + +Search functionality is a crucial aspect of any e-commerce platform, allowing users to quickly find products or +information they are looking for. In Magento 2, search is primarily based on Elasticsearch, an open-source, distributed +search engine. Elasticsearch provides advanced features like full-text search, relevance ranking, and filtering. + +To implement search in Magento 2, you need to have Elasticsearch configured and running. You can check the official +Magento 2 documentation for detailed instructions on Elasticsearch setup. + +## 2. Search Types + +Magento 2 supports two types of search: Quick Search and Advanced Search. + +### Quick Search + +Quick Search is the default search functionality in Magento 2. It enables users to perform a keyword-based search across +various attributes of products, like name, description, and SKU. The search query is matched against the indexed data, +and relevant results are displayed. + +Here's an example code snippet to perform a Quick Search in Magento 2: + +```php +$searchQuery = 'magento'; +$searchResults = $objectManager->create('Magento\CatalogSearch\Model\Search') + ->setQuery($searchQuery) + ->getSearchResult(); +``` + +### Advanced Search + +Advanced Search allows users to perform more complex searches by specifying multiple criteria, such as category, price +range, and attribute values. It provides a more refined search experience and helps users find products based on +specific requirements. + +To perform an Advanced Search in Magento 2, you can use the following code snippet: + +```php +$advancedSearchModel = $objectManager->create('Magento\CatalogSearch\Model\Advanced'); +$advancedSearchModel->addFilters([ + 'name' => 'magento', + 'price' => [ + 'from' => 10, + 'to' => 100 + ] +]); +$searchResults = $advancedSearchModel->getProductCollection(); +``` + +## 3. Search Indexing + +Search indexing is the process of preparing and organizing data for efficient search operations. In Magento 2, +Elasticsearch is responsible for indexing product data and attributes. By default, Magento 2 includes common product +attributes in the search index, like name, description, and SKU. However, you can customize the indexing process and +include additional attributes if needed. + +To customize the search index in Magento 2, you can create a custom module and define a `search_request.xml` file. This +file specifies the attributes to be included in the search index. Here's an example `search_request.xml` file: + +```xml + + + + + + + + + + + +``` + +After creating the `search_request.xml` file, you need to run the following command to apply the changes: + +``` +php bin/magento indexer:reindex catalogsearch_fulltext +``` + +## 4. Search Querying + +Querying is the process of retrieving relevant search results based on user input. Elasticsearch provides a powerful +Query DSL (Domain-Specific Language) that allows you to construct complex queries and apply filters, aggregations, and +sorting. + +In Magento 2, you can use the `SearchCriteria` class to build search queries. Here's an example code snippet to perform +a search query in Magento 2: + +```php +$searchCriteria = $objectManager->create('Magento\Framework\Api\SearchCriteriaBuilder') + ->addFilter('name', 'magento', 'like') + ->addSortOrder('price', 'ASC') + ->setPageSize(10) + ->create(); + +$searchResults = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface') + ->getList($searchCriteria); +``` + +## 5. Search Optimization + +Optimizing search functionality is crucial for improving performance and user experience. Here are some best practices +for search optimization in Magento 2: + +- Configure Elasticsearch settings for optimal performance, like the number of shards and replicas. +- Use appropriate analyzers to handle different languages and search requirements. +- Optimize attribute mapping to improve relevance and search accuracy. +- Leverage Elasticsearch features like aggregations, highlighting, and suggesters to enhance the search experience. + +Ensure to monitor and measure the performance of your search implementation using tools like Elasticsearch's Query +Profiler and Magento 2's built-in logging and reporting features. + +## 6. Conclusion + +This documentation provided an in-depth understanding of search implementation and customization in Magento 2. You +learned about Quick Search and Advanced Search, search indexing, querying, and optimization techniques. By following +these best practices, you can enhance the search functionality of your PHP-based e-commerce platform and provide a +seamless and efficient search experience to your users. + +Happy searching! diff --git a/security-features-in-magento-2.md b/security-features-in-magento-2.md index e69de29..492265c 100644 --- a/security-features-in-magento-2.md +++ b/security-features-in-magento-2.md @@ -0,0 +1,162 @@ +# Magento 2 Security Features Documentation + +[TOC] + +## Introduction + +Welcome to the documentation for security features in Magento 2! This guide will provide you with essential information +on how to secure your Magento 2 installation. It covers various security features and best practices that will help +protect your Magento store from potential threats. + +## Secure Configuration + +### File Permissions + +File permissions play a vital role in protecting your Magento installation. Ensure that all directories have the +appropriate permissions. For example, directories should have a permission of 755, and files should have a permission of +644. Restricting write permissions only to necessary files and directories is crucial to prevent unauthorized +modifications. + +```bash +find . -type f -exec chmod 644 {} \; +find . -type d -exec chmod 755 {} \; +``` + +### Secure Admin Panel + +To secure your admin panel, change the default URL path from `/admin` to a custom one. You can achieve this by modifying +the `admin/url/custom` configuration option in the `app/etc/env.php` file. + +```php +'backend' => [ + 'frontName' => 'your_custom_admin_path' +], +``` + +Additionally, use strong usernames and passwords for admin accounts and enforce regular password changes. Restrict +access to the admin panel to specific IP addresses using `.htaccess` or server configuration files. + +### Enable Two-Factor Authentication + +Enable two-factor authentication (2FA) for admin users to provide an extra layer of security. Magento 2 supports +multiple 2FA providers, such as Google Authenticator and Duo Security. Admin users can enable 2FA from their account +settings in the admin panel. + +## Secure Coding Practices + +### Input Validation + +Always validate user inputs to prevent potential security vulnerabilities, such as cross-site scripting (XSS) attacks +and SQL injections. Use Magento's built-in validation methods, such as `escapeHtml` or `validate-data`, to sanitize and +validate user inputs before processing them. + +```php +$validatedValue = $this->escapeHtml($value); +``` + +### Cross-Site Scripting (XSS) Prevention + +To prevent cross-site scripting attacks, make sure to escape user-generated content before displaying it in HTML +templates or JavaScript. Magento provides different methods like `escapeHtml`, `escapeJs`, or `escapeUrl` to properly +sanitize user data. + +```php +$escapedContent = $this->escapeHtml($content); +``` + +### SQL Injection Prevention + +When interacting with databases, always use Magento's built-in methods to prepare and execute SQL queries. This will +help prevent SQL injection attacks by automatically escaping user inputs. + +```php +$connection = $this->resourceConnection->getConnection(); +$query = $connection->select()->from('table')->where('column = ?', $value); +``` + +### Secure Password Storage + +Ensure that passwords are securely stored by using Magento's password hashing methods. Never store plain text passwords +in your database. Magento 2's password hashing algorithm uses bcrypt with a salt, which provides a strong level of +security. + +```php +$hash = $this->encryptor->getHash($password); +if ($this->encryptor->validateHash($password, $hash)) { + // Password is valid +} +``` + +## Secure File Handling + +### File Uploads + +Validate and sanitize file uploads to prevent potential security risks. Use Magento's built-in file validation methods, +such as `isValid`, to ensure that uploaded files meet your requirements. Also, consider storing uploaded files outside +of the web root directory to prevent direct access. + +```php +$fileUploader = $this->fileUploaderFactory->create(['fileId' => 'file']); +if ($fileUploader->isValid()) { + $fileUploader->save('path/to/save'); +} +``` + +### File Inclusion + +Avoid using user inputs directly in file inclusion functions to prevent directory traversal and remote file inclusion +attacks. Always validate and sanitize user inputs before using them in file inclusion operations. + +```php +$validatedFileName = $this->escapeHtml($fileName); +include 'path/to/files/' . $validatedFileName; +``` + +### File Download + +When providing file downloads to users, ensure that sensitive files are not accessible to unauthorized users. Implement +proper authentication and authorization checks before allowing file downloads. + +## User Authentication and Authorization + +### Password Policies + +Enforce strong password policies for all user accounts. Require password complexity, such as minimum length, the use of +alphanumeric characters, and a mix of upper and lowercase letters. Periodically prompt users to change their passwords +to enhance security. + +### Role-Based Access Control + +Implement role-based access control (RBAC) to grant appropriate permissions to users based on their roles. Magento 2 +provides a robust RBAC system that allows you to define roles and assign permissions to restrict access to certain areas +and resources. + +### Secure Session Management + +Ensure secure session management by using secure cookies, enabling secure session options, and enforcing session +timeouts. Make sure to set the `cookie_secure` and `cookie_httponly` options to `true` in your Magento configuration. + +## Secure Communication + +### HTTPS Configuration + +Configure your Magento installation to use HTTPS for all communication to ensure secure data exchange between clients +and the server. Obtain and install a valid SSL certificate and configure your web server accordingly. + +### Secure APIs + +When developing custom APIs, ensure that they are properly secured. Use OAuth or token-based authentication to protect +API endpoints and validate user access. Implement rate limiting and consider using API gateways for additional security. + +### Secure Payment Gateways + +When integrating payment gateways, choose trusted providers that adhere to PCI DSS (Payment Card Industry Data Security +Standard) compliance. Implement secure payment methods, such as tokenization, to prevent storing sensitive payment +information in your database. + +## Conclusion + +Congratulations! You have now learned about various security features and best practices to secure your Magento 2 +installation. By implementing these measures, you can protect your online store from potential security threats and +ensure a safe shopping experience for your customers. Remember to keep your Magento installation updated with the latest +security patches and follow Magento's security guidelines to stay ahead of evolving security risks. diff --git a/server-setup-and-configuration.md b/server-setup-and-configuration.md index e69de29..58cd2f0 100644 --- a/server-setup-and-configuration.md +++ b/server-setup-and-configuration.md @@ -0,0 +1,112 @@ +# Server Setup and Configuration Documentation + +[TOC] + +This documentation provides step-by-step instructions for setting up and configuring a server for hosting PHP-based +applications, specifically focusing on Magento 2. It assumes that the reader has some familiarity with programming, PHP, +and Magento 2. + +## Server Requirements + +Before setting up the server, make sure it meets the following minimum requirements: + +- Operating System: Linux, preferably CentOS or Ubuntu. +- Web Server: Apache or Nginx. +- Database Server: MySQL or MariaDB. +- PHP: Version 8.1 or later, with necessary extensions for Magento 2. + +## Software Stack + +### Web Server + +Choose either Apache or Nginx as your web server. Here's an example of installing and configuring Apache: + +```bash +$ sudo apt update +$ sudo apt install apache2 +``` + +After installation, configure Apache by editing the main configuration file located at `/etc/apache2/apache2.conf`. + +### Database Server + +Choose either MySQL or MariaDB as your database server. Here's an example of installing and configuring MySQL: + +```bash +$ sudo apt update +$ sudo apt install mysql-server +``` + +During the installation, you will be prompted to set the root password for MySQL. Make sure to choose a strong password. + +### PHP + +Magento 2 requires PHP 8.1 or later. Here's an example of installing PHP and necessary extensions: + +```bash +$ sudo apt update +$ sudo apt install php8.1 php8.1-cli php8.1-fpm php8.1-mysql php8.1-curl php8.1-gd php8.1-intl php8.1-mbstring php8.1-xml php8.1-zip +``` + +After installation, update the PHP configuration file located at `/etc/php/8.1/apache2/php.ini` and make the necessary +changes. + +## Server Setup + +### Installing and Configuring the Web Server + +1. Install the chosen web server software (Apache or Nginx) as described in the previous section. +2. Configure the web server to listen on the appropriate IP address and port. +3. Set up virtual hosts to point to your Magento 2 installation directory. +4. Enable necessary modules and configurations, such as SSL/TLS, if required. + +### Setting up the Database Server + +1. Install the chosen database server software (MySQL or MariaDB) as described in the previous section. +2. Secure the database server by running the security script provided by the database software. +3. Create a new database and database user for Magento 2, and grant the necessary privileges to the user. + +### Configuring PHP + +1. Update the PHP configuration file (`php.ini`) to set the necessary values. +2. Adjust PHP settings related to memory limits, file uploads, and execution time as needed. +3. Make sure the required PHP extensions for Magento 2 are enabled. + +## Magento 2 Specific Configuration + +### File and Directory Permissions + +Magento 2 requires specific file and directory permissions for proper functioning. Here's an example of setting +permissions: + +```bash +$ cd /var/www/html/magento2 +$ find var generated vendor pub/static pub/media app/etc -type f -exec chmod u+w {} + +$ find var generated vendor pub/static pub/media app/etc -type d -exec chmod u+w {} + +$ chmod u+x bin/magento +``` + +### URL Rewrites + +To enable user-friendly URLs in Magento 2, URL rewriting must be enabled. Here's an example of configuring URL rewrites +for Apache: + +```bash +$ sudo a2enmod rewrite +$ sudo service apache2 restart +``` + +For Nginx, add the following configuration snippet within the `server` block: + +```nginx +location / { + try_files $uri $uri/ /index.php?$args; +} +``` + +## Conclusion + +With this documentation, you should now have a server set up and properly configured to host PHP-based applications, +specifically Magento 2. Make sure to follow best practices for security and performance optimization. Remember to keep +your server software and dependencies up to date to ensure a stable and secure environment for your applications. Happy +coding! diff --git a/service-contracts.md b/service-contracts.md index e69de29..112da46 100644 --- a/service-contracts.md +++ b/service-contracts.md @@ -0,0 +1,162 @@ +# Service Contracts Documentation + +[TOC] + +Welcome to the Service Contracts documentation! In this guide, we will explore the concept of service contracts in the +context of PHP and Magento 2. Service contracts provide a standardized way to define and interact with modules and their +APIs. By adhering to service contracts, developers can ensure interoperability and maintainability of their codebase. + +## Introduction to Service Contracts + +In Magento 2, service contracts are interfaces that define a set of methods that can be used to interact with a specific +module or component. By defining a service contract, you establish a clear and consistent API for your module, allowing +other modules to interact with it in a standardized way. + +Service contracts provide several benefits, such as: + +* **Interoperability**: By adhering to service contracts, your module can seamlessly integrate with other modules that + depend on your API. This reduces coupling and promotes modularity in the Magento ecosystem. + +* **Maintainability**: Service contracts act as a contract between your module and its consumers. This means that you + can make changes to the underlying implementation of your module without breaking other modules that depend on it, as + long as you don't change the service contract itself. + +* **Testability**: Service contracts provide a clear interface that can be easily mocked and tested. This allows you to + write unit tests for your module and ensure its functionality in isolation. + +## Defining Service Contracts + +To define a service contract, you need to create an interface in your module. This interface will contain the methods +that define the API for your module. Let's take a look at an example: + +```php +myService = $myService; + } + + /** + * Example method that uses the service contract. + */ + public function doSomething() + { + $greeting = $this->myService->getGreeting("John"); + // Do something with the greeting... + } +} +``` + +In this example, we have a class `MyOtherClass` that has a dependency on the `MyServiceInterface`. We inject the service +contract into the class constructor and store it in a private property. Then, we can use the methods defined in the +service contract within the class methods. + +By using dependency injection, we ensure that the implementation of the service contract can be easily substituted or +mocked during testing. It also enforces the principle of loose coupling between modules. + +## Best Practices + +Here are some best practices to keep in mind when working with service contracts: + +1. **Keep service contracts focused**: Service contracts should be focused on a specific domain or functionality. Avoid + creating monolithic service contracts that encompass too many responsibilities. + +2. **Be consistent with naming**: Follow Magento's naming conventions when defining service contracts. This helps + maintain a standardized API across modules. + +3. **Document your service contracts**: Use PHPDoc annotations to document the parameters and return types of your + service contract methods. This makes it easier for developers to understand how to use your module. + +4. **Avoid breaking changes**: Once you have defined a service contract, avoid making breaking changes to it. If you + need to make changes, consider creating a new version of the service contract and mark the old one as deprecated. + +## Conclusion + +In this documentation, we have explored the concept of service contracts in PHP and Magento 2. Service contracts provide +a standardized way to define and interact with modules, promoting interoperability, maintainability, and testability. + +By defining and implementing service contracts, you can create modular and extensible code that can be easily integrated +with other modules in the Magento ecosystem. + +Remember to follow best practices, document your service contracts, and leverage dependency injection to ensure loose +coupling and easy testing of your modules. + +Happy coding with service contracts in Magento 2! diff --git a/soap-apis.md b/soap-apis.md index e69de29..d14b3fd 100644 --- a/soap-apis.md +++ b/soap-apis.md @@ -0,0 +1,120 @@ +# SOAP APIs Documentation + +[TOC] + +## Introduction + +This documentation provides a comprehensive guide to using SOAP APIs in PHP with Magento 2. It aims to equip developers +with the necessary knowledge and skills to successfully integrate and interact with SOAP APIs in their applications. The +document assumes a familiarity with PHP and Magento 2 concepts, such as object-oriented programming and web services. + +## 1. What is SOAP? + +SOAP (Simple Object Access Protocol) is a protocol for exchanging structured information in web services. It allows +applications to communicate over HTTP using XML-based messages. SOAP APIs provide a standardized way of interacting with +remote systems and accessing their functionality. + +Magento 2 offers a set of SOAP APIs to enable developers to integrate and interact with its e-commerce platform. These +APIs provide access to various resources, such as products, customers, orders, and more. By utilizing SOAP APIs, +developers can leverage the power of Magento 2 in their own applications. + +## 2. Setting Up a SOAP Client + +To interact with a SOAP API in PHP, you need to set up a SOAP client. The SOAP client acts as a bridge between your +application and the remote SOAP server. + +Here's an example of setting up a SOAP client in PHP using the built-in `SoapClient` class: + +```php +// Specify the WSDL URL of the SOAP server +$wsdlUrl = 'https://example.com/soap?wsdl'; + +// Create a new instance of the SOAP client +$client = new SoapClient($wsdlUrl); + +// Optionally, configure additional options +$options = [ + 'trace' => true, // Enable tracing of SOAP requests and responses + // Add more options if needed +]; + +// Pass the options to the SOAP client constructor +$client = new SoapClient($wsdlUrl, $options); +``` + +In the example above, we create a new instance of the `SoapClient` class by passing the WSDL URL of the SOAP server. We +can also provide additional options, such as enabling tracing of SOAP requests and responses. + +## 3. Making SOAP Requests + +Once you have set up a SOAP client, you can start making SOAP requests to the remote server. A SOAP request typically +consists of a method call with optional parameters. + +To invoke a SOAP method, you need to know its name and the expected parameters. The method names and parameter +structures are defined in the WSDL (Web Services Description Language) provided by the SOAP server. + +Here's an example of making a SOAP request in PHP using a SOAP client: + +```php +// Invoke a SOAP method +$result = $client->someMethod('param1', 'param2'); + +// Process the result +if ($result->success) { + // Handle successful response + $data = $result->data; +} else { + // Handle error response + $error = $result->error; +} +``` + +In the example above, we invoke the `someMethod` SOAP method with two parameters ('param1' and 'param2'). The result of +the method call is stored in the `$result` variable. We can then access the response data or handle any errors +accordingly. + +## 4. Handling SOAP Responses + +SOAP responses can have different structures depending on the specific API method being called. It's important to +understand the response structure to extract the relevant data. + +The response structure is defined in the WSDL provided by the SOAP server. You can inspect the WSDL or refer to the API +documentation to understand the response structure for each SOAP method. + +Here's an example of handling a SOAP response in PHP: + +```php +// Invoke a SOAP method +$result = $client->someMethod('param1', 'param2'); + +// Check if the SOAP request was successful +if ($result->success) { + // Handle successful response + $data = $result->data; +} else { + // Handle error response + $error = $result->error; +} +``` + +In the example above, we check the `success` property of the `$result` object to determine if the SOAP request was +successful. If it is, we can access the response data using the `data` property. Otherwise, we handle the error using +the `error` property. + +## 5. Examples + +To help illustrate the concepts discussed above, here are some concrete examples of using SOAP APIs in PHP with Magento +2: + +- Example 1: Retrieving a list of products from the catalog. +- Example 2: Creating a new customer account. +- Example 3: Placing an order for a product. + +Each example will provide step-by-step instructions and code snippets to guide you through the process. + +## Conclusion + +This documentation has covered the basics of using SOAP APIs in PHP with Magento 2. By following the guidelines and +examples provided, you should now be equipped to integrate and interact with SOAP APIs effectively. Remember to consult +the API documentation and the WSDL provided by the SOAP server for detailed information on specific API methods and +response structures. Happy coding! diff --git a/static-testing.md b/static-testing.md index e69de29..2ee760e 100644 --- a/static-testing.md +++ b/static-testing.md @@ -0,0 +1,109 @@ +# Static Testing Documentation + +[TOC] + +## Introduction + +Static testing is a crucial part of the software development process. It helps identify potential issues and improve the +overall quality of the codebase. In this documentation, we will explore the concept of static testing, its benefits, and +some best practices to follow when performing static testing in PHP and Magento 2. + +## What is Static Testing? + +Static testing, also known as static code analysis, is a technique used to analyze code without executing it. It +involves reviewing the source code to identify issues such as syntax errors, coding standards violations, potential +bugs, and security vulnerabilities. The goal is to catch these issues early in the development cycle, ensuring that the +software functions as intended and minimizing the need for manual testing and debugging. + +## Benefits of Static Testing + +### Early Detection of Issues + +One of the key advantages of static testing is its ability to detect issues at an early stage. By analyzing the code +before it is executed, static testing can identify potential problems that might otherwise go unnoticed until runtime. +This allows developers to address the issues promptly, reducing the cost and effort required to fix them later in the +development process. + +### Improved Code Quality + +Static testing helps improve the overall code quality by enforcing coding standards and best practices. It ensures that +the codebase is consistent and maintainable, making it easier for developers to understand, modify, and collaborate on +the code. By adhering to coding standards, the code becomes more readable, reducing the chances of introducing bugs or +errors. + +### Increased Security + +Security is a critical aspect of software development. Static testing can help identify security vulnerabilities in the +code, such as SQL injection, cross-site scripting (XSS), or insecure data handling. By addressing these issues early on, +developers can mitigate the risk of potential security breaches, protecting sensitive data and ensuring the software is +robust against attacks. + +## Static Testing in PHP and Magento 2 + +PHP is a popular programming language used in web development, including building Magento 2 applications. Magento 2, a +widely-used e-commerce platform, has its own set of coding standards and best practices. When performing static testing +in PHP and Magento 2, it is important to follow these guidelines to ensure the code is consistent, maintainable, and +secure. + +### Examples of Static Testing Tools + +There are several static testing tools available for PHP and Magento 2 that can help automate the process and identify +issues in the code. Let's take a look at a couple of popular tools: + +#### PHP_CodeSniffer + +PHP_CodeSniffer is a PHP library that checks code against a set of coding standards. It can detect violations and +provide detailed reports on coding style, formatting, and potential errors. Here's an example of how to use +PHP_CodeSniffer to analyze a PHP file: + +```bash +$ vendor/bin/phpcs /path/to/file.php +``` + +#### Magento Static Tests + +Magento provides its own set of static tests specifically designed for Magento 2 code. These tests check for coding +standards violations, security issues, and other potential problems. Here's an example of how to run Magento static +tests: + +```bash +$ vendor/bin/phpunit -c dev/tests/static/phpunit.xml.dist +``` + +### Best Practices for Static Testing + +To make the most of static testing in PHP and Magento 2, it is essential to follow some best practices. Here are a few +recommendations: + +#### Automate the Process + +Static testing can be time-consuming, especially in large codebases. To streamline the process, it is advisable to +automate static testing using tools like PHP_CodeSniffer or Magento Static Tests. By integrating these tools into your +development workflow, you can ensure that the code is consistently analyzed, even in complex projects. + +#### Create Custom Coding Standards + +While PHP_CodeSniffer and Magento Static Tests provide default coding standards, it is often necessary to customize them +to align with your project's requirements. By defining custom coding standards, you can enforce specific guidelines and +conventions that are relevant to your codebase. These custom standards should be documented and communicated to the +development team to maintain consistency. + +#### Regularly Review and Refactor Code + +Static testing should not be a one-time activity. It is crucial to regularly review and refactor the codebase to address +any issues identified during static testing. This ensures that the code remains clean, maintainable, and up to date with +the latest coding standards and best practices. + +#### Integrate Static Testing into CI/CD Pipelines + +To ensure that static testing is performed consistently, it is recommended to integrate it into your Continuous +Integration/Continuous Deployment (CI/CD) pipelines. By including static testing as a step in the pipeline, you can +catch issues early in the development process and prevent them from reaching production. + +## Conclusion + +Static testing is a valuable technique for improving the quality and security of software. By analyzing the code before +execution, static testing helps identify potential issues, enforce coding standards, and enhance the overall code +quality. In PHP and Magento 2 development, tools like PHP_CodeSniffer and Magento Static Tests can automate the static +testing process and provide actionable insights. By following best practices and integrating static testing into your +development workflow, you can ensure that your code is consistent, maintainable, and secure. diff --git a/system-xml.md b/system-xml.md deleted file mode 100644 index e69de29..0000000 diff --git a/system_xml.md b/system_xml.md new file mode 100644 index 0000000..c323e81 --- /dev/null +++ b/system_xml.md @@ -0,0 +1,165 @@ +# `system.xml` Reference Documentation + +[TOC] + +System.xml is a powerful configuration file used in PHP and Magento 2 to define system-level settings and +configurations. This file plays a crucial role in customizing the behavior and appearance of applications built on these +platforms. In this reference guide, we will explore the structure, syntax, and usage of system.xml, along with practical +examples to demonstrate its capabilities. + +## Introduction to System.xml + +System.xml is a configuration file that allows developers to define custom settings and configurations for PHP +applications, particularly those built on the Magento 2 platform. It provides a structured approach to manage various +aspects of application behavior, such as enabling/disabling features, setting default values, and specifying user +interface options. + +The system.xml file is typically located in the "etc" directory of a Magento 2 module, following the file naming +convention: `/etc/adminhtml/system.xml`. This file is XML-based, which means it follows the XML syntax and +requires strict adherence to its rules. + +## Structure and Syntax + +The system.xml file follows a hierarchical structure that consists of sections, groups, and fields. The root element of +this file is ``, and it contains one or more `
` elements, each representing a separate configuration +section. + +Here is an example of a basic system.xml file structure: + +```xml + + + +
+ +
+
+
+``` + +Within each `
`, you can define multiple `` elements, which further organize configuration fields. +Finally, within each ``, you can define individual `` elements to represent specific configuration +options. + +## Defining Configuration Sections + +Configuration sections group related settings together and provide a logical organization within the system.xml file. +Each `
` element must contain a unique `id` attribute to identify the section. + +Here is an example of defining a configuration section named "General" with an associated group: + +```xml + +
+ + my_custom_tab + Vendor_Module::config_general + + + +
+``` + +In the above example, we have specified various attributes for the `
` element: + +- `id`: A unique identifier for the section. +- `translate`: A translation key for the section label. +- `type`: The type of section (e.g., text, number). +- `sortOrder`: The position of the section in relation to other sections. +- `showInDefault`, `showInWebsite`, and `showInStore`: Flags indicating whether the section should be visible in various + configuration scopes (default, website, store). +- `label`: The label displayed for the section in the configuration UI. +- `tab`: The tab under which the section should be displayed in the configuration UI. +- `resource`: The ACL resource required to access the section. + +## Adding Configuration Fields + +Configuration fields represent specific settings within a section and are defined inside `` elements. +Each `` element must have a unique `id` attribute to identify the field. + +Here is an example of defining a text field within a group: + +```xml + + + + This is a sample text field. + Vendor\Module\Model\Config\Backend\MyTextField + validate-length maximum-length-255 + +``` + +In the above example, we have specified various attributes for the `` element: + +- `id`: A unique identifier for the field. +- `translate`: A translation key for the field label. +- `type`: The type of field (e.g., text, select, checkbox). +- `sort_order`: The position of the field in relation to other fields within the group. +- `show_in_default`, `show_in_website`, and `show_in_store`: Flags indicating whether the field should be visible in + various configuration scopes (default, website, store). +- `label`: The label displayed for the field in the configuration UI. +- `comment`: Additional information or description for the field. +- `backend_model`: The backend model responsible for handling the field's value. +- `validate`: Validation rules to enforce on the field's value. + +## Using Field Types + +System.xml supports various field types to cater to different requirements. Some commonly used field types +include `text`, `select`, `checkbox`, `textarea`, and `multiselect`. Each field type has specific attributes and options +that can be set. + +Here is an example of defining a select field: + +```xml + + + + Vendor\Module\Model\Config\Source\Options + +``` + +In the above example, the `source_model` attribute specifies a model that provides options for the select field. The +model should implement the `Magento\Framework\Option\ArrayInterface` interface to retrieve the available options. + +## Validation and Sanitization + +System.xml allows you to define validation rules for fields to ensure that the entered values meet specific criteria. +These rules are specified using the `` element within the `` definition. + +Here is an example of defining validation rules for a text field: + +```xml + + + + validate-length maximum-length-255 + +``` + +In the above example, we have used the `validate-length` validation rule to enforce a maximum length of 255 characters +for the field's value. + +## System.xml in Magento 2 + +In Magento 2, system.xml plays a vital role in configuring the behavior and appearance of modules. It allows merchants +to customize the settings of extensions and provides a user-friendly interface to manage these configurations. + +By defining sections, groups, and fields in system.xml, you can create a comprehensive configuration interface for your +module, enabling users to modify settings according to their specific needs. + +Magento 2 also provides various additional features and elements that can be combined with system.xml to enhance the +configuration experience, such as tabs, ACL resources, and scopes. + +## Conclusion + +System.xml is a powerful configuration file used in PHP and specifically in Magento 2 to define system-level settings +and configurations. This reference guide has provided an overview of the file's structure, syntax, and usage, along with +practical examples. + +Understanding system.xml is essential for developing and customizing Magento 2 modules, as it allows you to define and +manage configuration options for your extensions. By leveraging the features and techniques discussed, you can create +flexible and user-friendly applications that meet the unique requirements of your clients. diff --git a/testing-tools.md b/testing-tools.md index e69de29..de12f74 100644 --- a/testing-tools.md +++ b/testing-tools.md @@ -0,0 +1,161 @@ +# Testing Tools Documentation + +[TOC] + +## Introduction + +In this documentation, we will explore various testing tools that can be utilized for testing PHP and Magento 2 +applications. Testing is an essential aspect of software development, ensuring the quality and reliability of your code. +These tools facilitate the process by automating test execution, providing detailed reports, and assisting in code +coverage analysis. Let's dive into the world of testing tools! + +## PHPUnit + +PHPUnit is a widely-used testing framework for PHP applications. It provides a rich set of assertions, test case +management, and test execution capabilities. With PHPUnit, you can write unit tests to validate individual components of +your code, such as classes, methods, and functions. + +### Installation + +To install PHPUnit, you can utilize Composer, the dependency management tool for PHP. Open a terminal or command prompt +and execute the following command: + +```shell +composer require --dev phpunit/phpunit +``` + +### Example + +Let's take a look at a basic PHPUnit test case for a Magento 2 module. Assume we have a module named `My_Module` with a +class `MyClass` containing a `sum` method. We want to test if the method correctly adds two numbers. + +```php +class MyClassTest extends \PHPUnit\Framework\TestCase +{ + public function testSum() + { + $myClass = new \My\Module\MyClass(); + $result = $myClass->sum(2, 3); + + $this->assertEquals(5, $result); + } +} +``` + +In this example, we create a test case class `MyClassTest` that extends the `TestCase` class provided by PHPUnit. +The `testSum` method defines our test scenario. We create an instance of `MyClass`, call the `sum` method with +inputs `2` and `3`, and assert that the returned result is `5` using the `assertEquals` assertion. + +### Running Tests + +To execute PHPUnit tests, navigate to the root directory of your project in a terminal or command prompt and run the +following command: + +```shell +./vendor/bin/phpunit +``` + +PHPUnit will automatically discover and execute all test cases within your project. It will display the test results, +including the number of tests executed, failures, and errors. + +## Magento Testing Framework (MTF) + +The Magento Testing Framework (MTF) is a powerful tool specifically designed for testing Magento 2 applications. It +offers a comprehensive set of functionalities for integration, functional, and performance testing. MTF integrates with +PHPUnit and provides additional capabilities tailored for Magento 2, such as fixture management and test data +generation. + +### Installation + +MTF is part of the Magento 2 development environment. To install it, follow the Magento 2 installation instructions +provided by Magento. + +### Example + +Let's consider an example where we want to test a Magento 2 controller. We have a module named `My_Module` with a +controller `Index` that returns a JSON response. We want to verify if the response contains the expected data structure. + +```php +class IndexTest extends \Magento\TestFramework\TestCase\AbstractController +{ + public function testExecute() + { + $this->dispatch('my_module/index/index'); + $responseBody = $this->getResponse()->getBody(); + + $this->assertJson($responseBody); + $this->assertArrayHasKey('data', json_decode($responseBody, true)); + } +} +``` + +In this example, we create a test case class `IndexTest` that extends the `AbstractController` class provided by MTF. +The `testExecute` method dispatches a request to the `my_module/index/index` URL and retrieves the response body. We +assert that the response is in JSON format using `assertJson` and check if the decoded response body contains the `data` +key using `assertArrayHasKey`. + +### Running Tests + +To execute MTF tests, navigate to the root directory of your Magento 2 project in a terminal or command prompt and run +the following command: + +```shell +vendor/bin/phpunit -c dev/tests/integration/phpunit.xml.dist +``` + +MTF tests are typically stored in the `dev/tests/integration/testsuite` directory of your Magento 2 project. PHPUnit is +used to execute the tests, and the `-c` option specifies the PHPUnit configuration file to use. + +## Codeception + +Codeception is a versatile testing framework that supports various testing styles, including unit, functional, and +acceptance testing. It provides a simple and intuitive syntax for test case creation and execution. Codeception also +integrates with popular PHP frameworks, including Magento 2, making it an excellent choice for testing Magento +applications. + +### Installation + +To install Codeception, utilize Composer. Open a terminal or command prompt and execute the following command: + +```shell +composer require --dev codeception/codeception +``` + +### Example + +Let's demonstrate a basic Codeception acceptance test for a Magento 2 module. Assume we have a module named `My_Module` +with a page accessible at `/my_module/index/index`. We want to verify if the page title matches the expected value. + +```php +class MyModuleCest +{ + public function testHomePage(\AcceptanceTester $I) + { + $I->amOnPage('/my_module/index/index'); + $I->seeInTitle('My Module Home'); + } +} +``` + +In this example, we create a Cest class `MyModuleCest` that defines a test method `testHomePage`. The `$I` object +represents the test actor and provides various assertion and action methods. We use `$I->amOnPage` to navigate to the +desired URL and `$I->seeInTitle` to assert the presence of a specific text in the page title. + +### Running Tests + +To execute Codeception tests, navigate to the root directory of your project in a terminal or command prompt and run the +following command: + +```shell +vendor/bin/codecept run +``` + +Codeception will automatically discover and execute all test suites within your project. It will display the test +results, including the number of tests executed, failures, and errors. + +## Conclusion + +Testing tools like PHPUnit, MTF, and Codeception play a crucial role in ensuring the quality and stability of your PHP +and Magento 2 applications. With their capabilities, you can automate the testing process, validate your code, and +identify potential issues. By incorporating these tools into your development workflow, you can confidently release +software that meets the highest standards of quality. Happy testing! diff --git a/the-magento-application-and-service-contracts.md b/the-magento-application-and-service-contracts.md index e69de29..c90c5d3 100644 --- a/the-magento-application-and-service-contracts.md +++ b/the-magento-application-and-service-contracts.md @@ -0,0 +1,122 @@ +# Magento Application and Service Contracts Documentation + +[TOC] + +## Introduction + +Welcome to the documentation for the Magento Application and Service Contracts! In this guide, we will explore the key +concepts, usage, and benefits of using service contracts in your Magento 2 application development. We will also provide +concrete examples and code snippets to help you understand and implement these concepts effectively. + +## What are Service Contracts? + +Service contracts in Magento 2 provide a way to define a formal interface between modules. They act as a contract or +agreement that specifies how different modules can interact with each other. By defining service contracts, you can +ensure that modules rely on well-defined interfaces rather than directly accessing each other's implementation details. + +Using service contracts in your Magento 2 application has several benefits: + +- **Modularity**: Service contracts promote loose coupling between modules, allowing you to easily replace or extend + functionalities without affecting other parts of the system. +- **Compatibility**: Since service contracts define a common interface, modules can be developed independently without + worrying about breaking other modules that depend on them. +- **Flexibility**: Service contracts enable you to provide alternative implementations for different environments or + scenarios, such as different payment gateways or shipping providers. + +## Magento 2 Service Contract Architecture + +At the heart of the Magento 2 service contract architecture are three key components: + +1. **Service Interfaces**: These interfaces define the methods and data structures that represent a specific service, + such as customer management, order processing, or product management. Service interfaces reside in the `Api` module + of each Magento module and are typically named with the `Interface` suffix. + + For example, the service interface for customer management is `Magento\Customer\Api\CustomerRepositoryInterface`. + +2. **Service Contracts**: Service contracts define the data structures used by service interfaces. They specify the + input and output parameters, as well as any exceptions that may be thrown. Service contracts reside in the `Api/Data` + directory of each Magento module and are typically named without the `Interface` suffix. + + For example, the service contract for customer management is `Magento\Customer\Api\Data\CustomerInterface`. + +3. **Service Implementation**: The service implementation, also known as the service provider, is located in the `Model` + directory of each Magento module. It implements the service interface and provides the actual functionality. + +Now that we have a high-level understanding of the Magento service contract architecture, let's dive deeper into some +concrete examples. + +## Example: Creating a Customer using Service Contracts + +Suppose you want to create a new customer in your Magento 2 application. Instead of directly accessing the customer +model and database, you should use the service contracts to ensure compatibility and promote modularity. + +To create a customer using service contracts, follow these steps: + +1. First, retrieve an instance of the `CustomerRepositoryInterface` using dependency injection: + + ```php + use Magento\Customer\Api\CustomerRepositoryInterface; + + class MyCustomerCreationClass + { + protected $customerRepository; + + public function __construct( + CustomerRepositoryInterface $customerRepository + ) { + $this->customerRepository = $customerRepository; + } + + // ... + } + ``` + +2. Use the `CustomerRepositoryInterface` to create a new `CustomerInterface` instance and set the required customer + attributes: + + ```php + use Magento\Customer\Api\Data\CustomerInterface; + use Magento\Customer\Api\Data\CustomerInterfaceFactory; + + class MyCustomerCreationClass + { + protected $customerRepository; + protected $customerFactory; + + public function __construct( + CustomerRepositoryInterface $customerRepository, + CustomerInterfaceFactory $customerFactory + ) { + $this->customerRepository = $customerRepository; + $this->customerFactory = $customerFactory; + } + + public function createCustomer() + { + $customerData = [ + 'firstname' => 'John', + 'lastname' => 'Doe', + 'email' => 'john.doe@example.com' + ]; + + $customer = $this->customerFactory->create(['data' => $customerData]); + // Set additional customer attributes if needed + + return $this->customerRepository->save($customer); + } + } + ``` + +By following this approach, you ensure that your customer creation logic remains compatible even if the underlying +implementation of customer management changes in future Magento 2 versions or customizations. + +## Conclusion + +This documentation has provided an overview of Magento 2 service contracts and their benefits. By leveraging service +contracts, you can achieve modularity, compatibility, and flexibility in your Magento 2 application. + +We discussed the architecture of Magento 2 service contracts, including service interfaces, service contracts, and +service implementations. We also provided a concrete example of creating a customer using service contracts. + +We hope this guide has equipped you with the knowledge and understanding necessary to utilize Magento 2 service +contracts effectively in your own development projects. Happy coding! diff --git a/the-magento-application.md b/the-magento-application.md index e69de29..a07d567 100644 --- a/the-magento-application.md +++ b/the-magento-application.md @@ -0,0 +1,168 @@ +# Magento Application Documentation + +[TOC] + +## Introduction + +Welcome to the documentation for the Magento application. This document provides an in-depth guide to understanding and +using the features of Magento 2. Whether you are a developer, administrator, or store owner, this documentation will +help you navigate through the various aspects of the Magento platform. + +## 1. Installation + +To install Magento, follow these steps: + +1. Download the latest version of Magento from the official website. +2. Extract the downloaded archive to your web server root directory. +3. Set the file permissions and ownership to ensure security. +4. Create a new database and configure the database connection in `app/etc/env.php`. +5. Run the Magento installation script from the command line. + +Please refer to the official Magento installation guide for detailed instructions and troubleshooting tips. + +## 2. Configuration + +Magento provides a comprehensive configuration system that allows you to customize various aspects of your store. The +configuration options are stored in the database and can be accessed through the admin panel. + +To configure your Magento store, navigate to **Stores > Configuration** in the admin panel. Here, you will find various +sections such as General, Catalog, Sales, and more. Each section contains multiple settings that can be adjusted +according to your requirements. + +For example, to configure the General settings, navigate to **Stores > Configuration > General**. Here, you can set the +store name, email addresses, base URLs, and other general settings. + +## 3. Themes and Layouts + +Magento uses a theme-based system to control the appearance of your store. A theme is a collection of files that +determine the layout, design, and functionality of your store's frontend. + +To create a new theme, follow these steps: + +1. Create a new directory under `app/design/frontend` for your theme. +2. Copy the necessary files from the parent theme or the Magento Blank theme. +3. Customize the files according to your requirements. +4. Specify your theme in the admin panel under **Content > Design > Configuration**. + +Magento also provides a layout system that allows you to control the structure and content of your store's pages. Layout +files are written in XML and define the structure of blocks and containers. + +For example, to add a new block to the homepage, create a layout file named `cms_index_index.xml` in your theme's layout +directory. Inside the file, define the block using XML tags: + +```xml + + + + +``` + +## 4. Modules and Extensions + +Magento is highly extensible through the use of modules and extensions. A module is a self-contained unit of +functionality that can be added to your store to enhance its features or customize its behavior. + +To create a new module, follow these steps: + +1. Create a new directory under `app/code` for your module. +2. Define the module's configuration file `module.xml` to specify its name, version, and dependencies. +3. Create the necessary directories and files for your module's functionality. +4. Enable the module through the command line or the admin panel. + +Extensions, on the other hand, are pre-built packages that can be installed in your Magento store to add new features or +integrate with third-party services. Extensions can be downloaded from the Magento Marketplace or other trusted sources. + +To install an extension, follow the installation instructions provided by the extension's developer. Usually, this +involves copying the extension files to the appropriate directories and running a setup script. + +## 5. Catalog Management + +Managing your store's catalog is a crucial part of running an online business. Magento provides a comprehensive set of +tools to help you manage your products, categories, and attributes. + +To add a new product, follow these steps: + +1. Navigate to **Catalog > Products** in the admin panel. +2. Click on **Add Product** and choose the product type (simple, configurable, virtual, etc.). +3. Fill in the required information such as name, price, and stock status. +4. Configure additional settings such as categories, images, and attributes. +5. Save the product to make it available in your store. + +You can also manage product categories, attributes, and attribute sets from the respective sections in the admin panel. + +## 6. Order Management + +Magento provides a robust order management system that allows you to manage and process customer orders efficiently. +From the admin panel, you can view, edit, and fulfill orders, as well as generate invoices, shipments, and credit memos. + +To view and manage orders, navigate to **Sales > Orders** in the admin panel. Here, you can search for orders, view +their details, and perform various actions such as canceling, shipping, or creating invoices. + +You can also configure various order-related settings such as payment methods, shipping methods, and tax settings from +the respective sections in the admin panel. + +## 7. Customer Management + +Managing customer accounts and profiles is essential for providing a personalized shopping experience. Magento offers a +range of features to help you manage customer information, addresses, and account settings. + +To view and manage customer accounts, navigate to **Customers > All Customers** in the admin panel. Here, you can search +for customers, view their details, and perform actions such as creating orders on behalf of the customer or resetting +their password. + +You can also configure customer-related settings such as registration options, account sharing, and email templates from +the respective sections in the admin panel. + +## 8. Promotions and Discounts + +Creating promotions and discounts is a powerful way to attract customers and increase sales. Magento provides a flexible +promotion system that allows you to create various types of promotions, such as discounts, coupons, and free shipping +offers. + +To create a new promotion, navigate to **Marketing > Promotions** in the admin panel. Here, you can create shopping cart +price rules, catalog price rules, and related promotions. + +For example, to create a 10% discount on a specific category of products, you can create a shopping cart price rule with +the following settings: + +- Rule Information: Set the conditions and actions for the promotion. +- Labels: Define the labels and descriptions for the promotion. +- Coupons: Optionally, generate unique coupon codes for the promotion. + +## 9. Performance Optimization + +Optimizing the performance of your Magento store is crucial for providing a smooth and fast user experience. Magento +offers various performance optimization techniques and configurations to improve the speed and efficiency of your store. + +Some performance optimization strategies include: + +- Enabling caching and leveraging full-page caching. +- Minifying CSS and JavaScript files. +- Optimizing images and using lazy loading. +- Enabling flat catalog and indexing. + +Additionally, you can use performance profiling tools to identify bottlenecks and optimize specific areas of your store. + +## 10. Security + +Ensuring the security of your Magento store is of utmost importance to protect your data, customer information, and +business reputation. Magento provides several security features and best practices to help you maintain a secure store. + +Some security measures to consider include: + +- Keeping your Magento installation up to date with the latest patches and security releases. +- Implementing secure coding practices and validating user input. +- Enabling two-factor authentication for admin accounts. +- Regularly backing up your store's data and database. + +By following these security practices, you can minimize the risk of vulnerabilities and ensure the integrity of your +Magento store. + +## Conclusion + +This documentation provides a comprehensive guide to understanding and using the Magento platform. From installation to +configuration, catalog management to order processing, and performance optimization to security, Magento offers a wide +range of features and capabilities to support your online business. + +By familiarizing yourself with the concepts and techniques discussed in this documentation, you will be equipped with +the knowledge and skills to build, customize, and manage your Magento store effectively. diff --git a/theme-development.md b/theme-development.md index e69de29..728dc6e 100644 --- a/theme-development.md +++ b/theme-development.md @@ -0,0 +1,206 @@ +# Theme Development Documentation + +[TOC] + +## Introduction + +This documentation provides a comprehensive guide to theme development in Magento 2. It covers the essential concepts, +techniques, and best practices required to create custom themes for Magento 2 stores. + +Please note that this documentation assumes a familiarity with programming concepts, particularly PHP and Magento 2. If +you are new to Magento 2 or programming, it is recommended to familiarize yourself with these topics before proceeding +further. + +## Theme Anatomy + +Before diving into theme development, it is essential to understand the structure and components of a Magento 2 theme. A +theme consists of the following main elements: + +1. **Theme Files**: These include layout XML files, template files (`.phtml`), CSS files, JavaScript files, and other + assets. +2. **Theme Configuration**: Magento 2 uses XML configuration files to define theme-specific settings, such as logo, + colors, and fonts. +3. **Theme Inheritance**: Themes can inherit from other themes, allowing for customization and extension of existing + themes. +4. **Theme Layouts**: Layout XML files control the structure and composition of pages in a Magento 2 store. +5. **Theme Templates**: Template files define the HTML structure and content of various components in a theme. +6. **Theme CSS and JavaScript**: CSS and JavaScript files control the appearance and behavior of a theme. +7. **Theme Deployment**: Themes need to be deployed to make them available to a Magento 2 store. + +## Creating a Custom Theme + +To create a custom theme in Magento 2, follow these steps: + +1. Create a new directory for your theme under `app/design/frontend/{Vendor}/{theme}`. For example, if your theme is + called "MyTheme" and your vendor is "Acme", the path would be `app/design/frontend/Acme/MyTheme`. +2. Create a `theme.xml` file within your theme's directory. This file defines the theme's name, parent theme, and other + configuration options. Here's an example: + +```xml + + + MyTheme + Magento/blank + + media/preview.jpg + + +``` + +3. Create a `registration.php` file in your theme's directory. This file registers your theme and makes it available to + Magento 2. Here's an example: + +```php +` tag. Here's an example: + +```xml + +Magento/luma +``` + +By inheriting from a parent theme, you can override specific files, add new files, and modify theme settings to achieve +the desired customization. + +## Theme Layouts + +Layouts in Magento 2 define the structure and composition of pages. A layout is defined using XML files located in +the `app/design/frontend/{Vendor}/{theme}/Magento_Theme/layout` directory. Each layout file controls a specific page or +block within a page. For example, the `default.xml` file controls the structure of the entire store, while +the `cms_index_index.xml` file controls the homepage layout. + +Layout files consist of blocks, containers, and references, which define the structure of a page. Blocks represent +individual components, such as header, footer, and sidebar, while containers act as placeholders for blocks. References +are used to specify the location of blocks within containers. + +Here's an example of a simple layout XML file that adds a block to the homepage: + +```xml + + + + + + + + +``` + +This example adds a block named "custom.block" to the "content" container. The block uses the template +file `custom_template.phtml` from the `Magento_Theme` module. + +You can create and customize layout XML files within your theme to control the structure of various pages in your +Magento 2 store. + +## Theme Templates + +Template files in Magento 2 define the HTML structure and content of various components within a theme. The template +files have the extension `.phtml` and are located in the `app/design/frontend/{Vendor}/{theme}/Magento_Theme/templates` +directory. + +To customize a particular component, you can override its template file in your custom theme. For example, to override +the header template, create a file called `header.phtml` within your theme's template directory and modify it as per +your requirements. + +You can also use template files to display dynamic data or perform complex logic by using PHP code. However, it is +recommended to keep the logic to a minimum and separate it from the presentation using blocks, which we will discuss in +the next section. + +## Theme CSS and JavaScript + +CSS and JavaScript files control the appearance and behavior of a theme. In Magento 2, these files are located in +the `app/design/frontend/{Vendor}/{theme}/web` directory. + +To add custom CSS or JavaScript to your theme, create a directory structure within the `web` directory that mirrors the +file structure you want to override. For example, to override the default CSS file of a theme, create a file +called `styles.css` within the `css` directory of your custom theme. + +You can also add new CSS or JavaScript files and reference them in your layout XML files. This allows for greater +flexibility in customizing and extending the behavior of your theme. + +## Overriding Core Theme Files + +Magento 2 allows you to override core theme files without modifying the original files. By placing a file with the same +name and location in your custom theme, Magento 2 will prioritize the file from your custom theme over the core file. + +For example, to override the default header template (`header.phtml`), create a file with the same name and location in +your custom theme: `app/design/frontend/{Vendor}/{theme}/Magento_Theme/templates/html/header.phtml`. Any modifications +made to this file will be reflected in your store, without touching the original core file. + +This approach ensures that your customizations remain separate from the core codebase, making it easier to upgrade +Magento 2 in the future. + +## Theme Configuration + +Magento 2 allows you to configure various theme settings, such as logo, colors, fonts, etc., using theme configuration +files. These files are located in the `app/design/frontend/{Vendor}/{theme}/etc` directory. + +To configure your theme, create a file called `view.xml` within your theme's `etc` directory. This file defines various +settings, such as image sizes, color swatches, and other visual aspects of your theme. Here's an example: + +```xml + + + + + + 240 + 300 + + + + +``` + +This example defines the dimensions for the category page grid image. You can customize this file to configure various +aspects of your theme as per your requirements. + +## Theme Deployment + +Once you have developed and customized your theme, it needs to be deployed to make it available to your Magento 2 store. +Magento 2 provides a set of commands to deploy themes and other assets. + +To deploy your theme, run the following command from your Magento 2 root directory: + +``` +bin/magento setup:static-content:deploy +``` + +This command generates static files for all enabled themes, including your custom theme, and places them in the +appropriate directories to be served by the web server. + +After the deployment, your custom theme will be available for selection in the Magento 2 admin panel under **Content > +Design > Configuration**. + +## Conclusion + +This documentation has covered the fundamental concepts and techniques required for theme development in Magento 2. By +understanding the theme anatomy, creating custom themes, leveraging theme inheritance, working with layouts, templates, +CSS, JavaScript, and overriding core theme files, you can create visually appealing and customized themes for your +Magento 2 store. + +Remember to adhere to best practices, maintain separation between custom and core code, and regularly test your themes +to ensure compatibility and performance. With these skills and knowledge, you are well-equipped to build stunning and +engaging themes in Magento 2. diff --git a/troubleshooting-common-installation-issues.md b/troubleshooting-common-installation-issues.md index e69de29..428b3fc 100644 --- a/troubleshooting-common-installation-issues.md +++ b/troubleshooting-common-installation-issues.md @@ -0,0 +1,112 @@ +# Troubleshooting Common Installation Issues + +[TOC] + +This documentation aims to provide solutions to common installation issues encountered while setting up a PHP-based +e-commerce platform, specifically Magento 2. The instructions assume that you have a basic understanding of programming +concepts and the Magento 2 framework. + +## 1. Server Requirements + +Before troubleshooting any installation issues, make sure your server meets the minimum requirements for running Magento +2. These requirements include PHP version, extensions, and server configurations. Consult the official Magento 2 +documentation or the system requirements provided by your hosting provider for the exact specifications. + +## 2. Invalid Credentials for Database Connection + +One common installation issue occurs when Magento 2 fails to connect to the database due to incorrect credentials. To +resolve this, verify that the database credentials specified in the `app/etc/env.php` file are correct. For example: + +```php +'db' => [ + 'connection' => [ + 'default' => [ + 'host' => 'localhost', + 'dbname' => 'magento', + 'username' => 'magento_user', + 'password' => 'magento_password', + 'active' => '1', + ], + ], +], +``` + +Ensure the host, dbname, username, and password values match those provided by your database administrator or hosting +provider. + +## 3. File and Directory Permissions + +Magento 2 requires specific file and directory permissions to function properly. Incorrect permissions can result in +installation issues, such as blank pages or access denied errors. Here are some general guidelines: + +- All directories should have permissions set to `770`. +- All files should have permissions set to `660`. +- The `var`, `pub/static`, and `generated` directories, as well as their subdirectories, should have permissions set + to `777`. + +To set permissions, navigate to your Magento 2 root directory and execute the following commands: + +```bash +chmod -R 770 var pub/static generated +chmod 660 app/etc/env.php +``` + +This ensures the necessary read, write, and execute permissions are set correctly. + +## 4. Missing Required PHP Extensions + +Magento 2 relies on various PHP extensions to function properly. If you encounter an error indicating a missing +extension, you need to install it. Here's an example: + +``` +PHP Extension xsl is not loaded. +``` + +In this case, you would need to install the XSL extension for PHP. The exact method varies depending on your operating +system and PHP setup. For example, on Ubuntu, you can install it using the following command: + +```bash +sudo apt-get install php-xsl +``` + +Refer to your operating system's documentation or consult with your hosting provider to install the required extensions. + +## 5. Memory Limit Exceeded + +During installation or operation, Magento 2 may encounter memory limit errors. This typically occurs due to insufficient +memory allocated to PHP. To resolve this, you can increase the memory limit by editing the PHP configuration +file (`php.ini`). + +Locate the `memory_limit` directive and adjust its value to a higher limit. For example: + +``` +memory_limit = 512M +``` + +Save the file and restart your web server to apply the changes. + +## 6. Clearing Cache and Generated Files + +If you encounter unexpected issues during installation or after making changes to your Magento 2 installation, it's +often helpful to clear the cache and generated files. Magento 2 provides command-line tools for this purpose. + +To clear the cache, run the following command from your Magento 2 root directory: + +```bash +bin/magento cache:clean +``` + +To regenerate static files, run the following command: + +```bash +bin/magento setup:static-content:deploy +``` + +These commands ensure that any cached data or outdated generated files are removed and regenerated. + +## Conclusion + +This documentation has provided solutions to common installation issues encountered while setting up Magento 2. By +following these troubleshooting steps, you should be able to address most problems you may encounter during the +installation process. Remember to consult the official Magento 2 documentation or seek assistance from the Magento +community if you encounter any issues that remain unresolved. diff --git a/ui-components.md b/ui-components.md index e69de29..151afc7 100644 --- a/ui-components.md +++ b/ui-components.md @@ -0,0 +1,135 @@ +# UI Components Documentation + +[TOC] + +This documentation provides an overview and detailed explanation of UI components in Magento 2, specifically focusing on +their usage, structure, and customization. UI components are an integral part of Magento's frontend development, +allowing developers to create interactive user interfaces with reusable code. + +## Introduction to UI Components + +UI components are JavaScript objects that define the structure and behavior of a specific element on a webpage. They are +an essential part of the Magento 2 frontend architecture and follow a declarative programming approach. Each UI +component can have its own set of properties, methods, and data that determine how it behaves and interacts with other +components. + +In Magento 2, UI components are widely used for various tasks, such as rendering grids, forms, and other UI elements. +They simplify the development process by providing a standardized way of building interactive interfaces and promoting +code reusability. + +## UI Component Structure + +A UI component consists of several essential elements: + +1. **XML Configuration**: Each UI component is defined in an XML file, typically located in + the `view/[area]/ui_component` directory of a Magento module. This XML configuration specifies the component's name, + template, data source, and other properties. + + Example XML configuration for a grid UI component: + ```xml + + + + + + + ``` + +2. **UI Component JavaScript**: The XML configuration references a JavaScript file that provides the component's logic + and behavior. This JavaScript file is typically located in the `view/[area]/web/js/[component_name].js` directory. + + Example JavaScript code for a grid UI component: + ```javascript + define([ + 'Magento_Ui/js/grid/listing' + ], function (Listing) { + 'use strict'; + + return Listing.extend({ + defaults: { + // Component defaults + }, + + // Component methods and properties + }); + }); + ``` + +3. **Template**: The UI component's template file defines the HTML structure and appearance of the component. It is + referenced in the XML configuration and typically located in the `view/[area]/web/template` directory. + + Example template code for a grid UI component: + ```html + + +
+ ``` + +## UI Component Usage + +To use a UI component in a Magento 2 module, follow these steps: + +1. Create an XML configuration file for the component in the appropriate module's `view/[area]/ui_component` directory. +2. Define the component's properties and logic in a JavaScript file located in + the `view/[area]/web/js/[component_name].js` directory. +3. Create the component's template file in the `view/[area]/web/template` directory, specifying the HTML structure of + the component. +4. Reference the component in the desired layout file, such as `view/[area]/layout/[layout_name].xml`, using + the `` tag. + + Example usage of a grid UI component in a layout file: + ```xml + + + + ``` + +The UI component will then be rendered according to its XML configuration, JavaScript logic, and HTML template. + +## Customizing UI Components + +Magento 2 provides several ways to customize UI components to suit specific requirements: + +1. **Extending Components**: Developers can extend existing UI components to modify or add functionality. This is + achieved by creating a new XML configuration file that references the base component and overrides specific + properties or methods. + + Example XML configuration for extending a grid UI component: + ```xml + + + + + + + ``` + +2. **Modifying Templates**: Developers can customize the appearance of a UI component by modifying its template file. + This involves overriding the default template in a custom theme or module. + + Example template modification for a grid UI component: + ```html + + +
+ ``` + +3. **Manipulating Data**: UI components often interact with data sources, such as APIs or databases. Developers can + customize a component's data handling by extending or modifying the corresponding JavaScript file. + + Example data manipulation in a grid UI component: + ```javascript + return Listing.extend({ + fetchData: function () { + // Custom data retrieval logic + }, + // Other custom methods and properties + }); + ``` + +## Conclusion + +UI components are a fundamental part of Magento 2 frontend development, providing a structured and reusable approach to +building interactive user interfaces. This documentation has provided an introduction to UI components, explained their +structure and usage, and described methods for customizing them. By following these guidelines and leveraging the power +of UI components, developers can create highly functional and visually appealing interfaces in their Magento 2 projects. diff --git a/unit-testing.md b/unit-testing.md index 7c21cbe..a95d5ee 100644 --- a/unit-testing.md +++ b/unit-testing.md @@ -1,302 +1,158 @@ -# Unit Testing in Magento 2 +# Unit Testing Documentation -- [Overview](#overview) -- [Setup and Configuration](#setup-and-configuration) -- [Creating a Unit Test](#creating-a-unit-test) -- [Running Unit Tests](#running-unit-tests) -- [Run Unit Tests within PHPStorm](#run-unit-tests-within-phpstorm) -- [Write Testable Code](#write-testable-code) -- [Best Practices](#best-practices) -- [Mocking](#mocking) -- [DocBlock Annotations](#docblock-annotations) -- [Code Coverage](#code-coverage) -- [Run Unit Tests in CI](#run-unit-tests-in-ci) - - [GitHub Actions](#github-actions) - - [GitLab Pipelines](#gitlab-pipelines) -- [Summary](#summary) +[TOC] -## Overview +## Introduction - +Unit testing is an essential practice in software development that involves testing individual units or components of +code to ensure their correctness. In this documentation, we will explore the fundamentals of unit testing, its benefits, +and how to write effective unit tests for PHP and Magento 2. -Unit testing is a critical part of software development. It involves testing individual units of code (such as functions -or methods) to ensure they perform as expected. In Magento 2, PHPUnit is the testing framework used for writing and -executing unit tests. +## Benefits of Unit Testing -Magento 2 has a solid structure for unit tests that separates them from other types of tests (like integration, -functional, and performance tests). In a typical Magento 2 module, the unit tests are located in the `Test/Unit` -directory of the module. +Unit testing offers numerous benefits, including: -## Setup and Configuration +1. **Bug Prevention**: By testing individual units of code, potential bugs and errors can be identified and fixed early + in the development process, reducing the overall cost and effort required. - +2. **Code Maintainability**: Unit tests act as a safety net when making changes to the codebase. They provide assurance + that existing functionality will not break due to modifications, making it easier to refactor and improve code. -Before you begin, ensure you have PHPUnit installed. Magento 2 recommends using the latest stable PHPUnit version -supported by your PHP installation. +3. **Documentation**: Unit tests serve as living documentation, providing examples of how the code should be used and + the expected behavior of its components. -You can install PHPUnit globally or as a part of your project via Composer. The following command installs PHPUnit -globally: +4. **Rapid Feedback**: Unit tests enable quick feedback on code changes, as they can be executed independently and do + not require the entire application to be running. -```bash -composer global require phpunit/phpunit -``` - -After installing PHPUnit, validate the installation by checking the version: +5. **Collaboration**: Unit tests facilitate collaboration among developers by providing a common understanding of code + functionality and behavior. -```bash -phpunit --version -``` +## Unit Testing in PHP -## Creating a Unit Test +### PHPUnit - +PHPUnit is a widely used unit testing framework for PHP. It provides a rich set of assertions, test runners, and other +utilities to aid in writing effective unit tests. Let's look at some examples of how to write unit tests using PHPUnit. -In this section, we'll create a simple unit test for a hypothetical SampleModule in Magento 2. - -1. Navigate to your module's directory and create a new Test/Unit directory if it doesn't exist. - -```bash -mkdir -p app/code/Vendor/SampleModule/Test/Unit -``` - -2. Inside the `Test/Unit` directory, create a new test class. In this case, we'll create `SampleTest.php`: +To begin, create a new test class, `MyClassTest`, that extends the `PHPUnit\Framework\TestCase` class: ```php -assertEquals(10, 5 + 5); - } + // Test methods will be written here } ``` -In this example, `testSampleMethod` is a simple test case that asserts whether `5 + 5` equals `10`. +#### Asserting Equality -## Running Unit Tests +PHPUnit provides various assertion methods to validate expected outcomes. One common assertion is to check for equality +between expected and actual values. For example: - - -To run the unit test, use the phpunit command from the root directory of your Magento 2 installation: - -```bash -./vendor/bin/phpunit -c dev/tests/unit/phpunit.xml.dist app/code/Vendor/SampleModule/Test/Unit -``` - -This command tells PHPUnit to use the configuration specified in phpunit.xml.dist and run the tests located -in `app/code/Vendor/SampleModule/Test/Unit`. - -To run an entire suite (i.e., all tests in a directory), specify the directory path: - -```bash -./vendor/bin/phpunit -c dev/tests/unit/phpunit.xml.dist app/code/Vendor/SampleModule/Test/Unit +```php +public function testAddition() +{ + $result = 2 + 2; + $this->assertEquals(4, $result); +} ``` -The output should look something like this: +In the above example, the `assertEquals` method checks whether the `$result` variable is equal to `4`. -```bash -PHPUnit X.X.X by Sebastian Bergmann and contributors. +#### Mocking Dependencies -. 1 / 1 (100%) +When testing code that has dependencies, it's often necessary to create mocks or stubs to isolate the unit being tested. +PHPUnit provides a `getMock()` method to create mock objects. -Time: X ms, Memory: X MB +```php +public function testSomethingWithMock() +{ + $dependencyMock = $this->getMockBuilder(DependencyClass::class) + ->getMock(); -OK (1 test, 1 assertion) + // Use the mock object within the test +} ``` -## Run Unit Tests within PHPStorm - - - -To run tests within PHPStorm, follow these steps: - -Open the `Settings/Preferences` dialog (`Ctrl+Alt+S`), go to `Languages & Frameworks | PHP | Test Frameworks`. -Click `+`, and choose `PHPUnit Local`. -Configure the PHPUnit library and settings. -After the configuration, go to your test, right-click on it and select Run `test-name`. - -## Write Testable Code +In the above example, the `getMockBuilder()` method creates a mock object of the `DependencyClass`. This allows the test +to control the behavior of the dependency and focus solely on the unit being tested. - +For more advanced mocking scenarios, PHPUnit also supports the use of mock libraries such as Mockery and Prophecy. -Writing testable code involves designing your code in a way that makes it easier to isolate and test individual units. -Some tips for writing testable code include: +## Unit Testing in Magento 2 -**Single Responsibility**: Each method/class should have a single responsibility. It should do one thing and do it well. -**Avoid Static Methods**: Static methods can't be mocked or stubbed, making them difficult to test. -**Dependency Injection**: Using dependency injection helps make your code more flexible and easier to test. +### Magento Testing Framework (MTF) -## Best Practices +Magento 2 provides a dedicated testing framework called Magento Testing Framework (MTF) for writing unit tests. MTF +extends PHPUnit and introduces additional features specific to Magento. - +To write unit tests in Magento 2, follow these steps: -**Use Descriptive Test Method Names**: The method name should describe what the test does. For example, -`testUserIsCreatedWithValidInput` is descriptive and you can understand what the test does by looking at its name. -**One Assertion Per Test Method**: Ideally, each test should only have one assertion. This makes the tests more readable -and -errors easier to pinpoint. -**Don't Test Everything**: It's important to note that not all code needs to be tested. If it's already being tested -elsewhere or it's part of the framework's functionality, there's usually no need to test it again. - - -## Mocking - - - -Mocking is a process used in unit testing when the unit of code has external dependencies. A mock object is a dummy -implementation that simulates the behavior of a real object. +1. Create a new test class that extends the `Magento\FunctionalTestingFramework\TestCase\TestCase` class: ```php -sampleMock = $this->getMockBuilder(Sample::class) - ->disableOriginalConstructor() - ->getMock(); - } - - public function testSampleMethod() - { - $this->sampleMock->method('getNumber') - ->willReturn(5); - - $this->assertEquals(10, $this->sampleMock->getNumber() + 5); - } + // Test methods will be written here } ``` -In this example, `Sample::class` is a dependency of the unit being tested. We create a mock for this dependency and -define -its behavior to return `5` when getNumber is called. - -## DocBlock Annotations - - - -DocBlocks or PHPDoc comments are used to provide metadata for your codebase. These comments can be parsed by tools to -generate human-readable documentation. - -PHPUnit uses these annotations to control the behavior of your tests. Here are some commonly used annotations: - -- `@test`: This annotation can be used to mark a method as a test method. -- `@dataProvider`: This annotation can be used to specify a method that returns data for a test. -- `@depends`: This annotation can be used to specify that a test depends on another test. -- `@group`: This annotation allows you to group tests together so you can run a set of tests separately from others. - -Example: +2. Use the Magento testing APIs to interact with the Magento system and test the desired functionality. ```php -/** - * @test - * @dataProvider additionProvider - */ -public function testAdd($a, $b, $expected) +public function testMyCustomModule() { - $this->assertEquals($expected, $a + $b); + $this->loginAdminUser('admin', 'password'); + $this->openAdminPage('my_custom_module'); + $this->seePageTitle('My Custom Module'); + // Additional assertions and interactions } - -public function additionProvider() -{ - return [ - [1, 2, 3], - [0, 0, 0], - [-1, -1, -2], - ]; -} -``` - -In this example, `@test` marks `testAdd` as a test method, and `@dataProvider` specifies `additionProvider` as the -method -providing data for the `testAdd` test. - -This concludes our in-depth guide on unit testing in Magento 2. Remember that good tests can help you catch bugs early, -make your codebase more maintainable, and save you, your team, and your users a lot of trouble down the line. Happy -testing! - - -## Code Coverage - - - -Code coverage is a measure that describes the degree to which the source code of a program is executed when a particular -test suite runs. To generate a code coverage report, PHPUnit needs `Xdebug` or `pcov` installed. - -You can enable code coverage in the PHPUnit configuration file (phpunit.xml) or run the command: - -```bash -./vendor/bin/phpunit -c dev/tests/unit/phpunit.xml.dist --coverage-html coverage app/code/Vendor/SampleModule/Test/Unit ``` -This command will generate an HTML report in the `coverage` directory. - -## Run Unit Tests in CI - - - -## GitHub Actions - -In your `.github/workflows` directory, create a new file called `run-tests.yml` and populate it: - -```yaml -name: Run PHPUnit Tests - -on: [ push, pull_request ] - -jobs: - build: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v3 - - - name: Validate composer.json and composer.lock - run: composer validate - - - name: Install Dependencies - run: composer install --prefer-dist --no-progress --no-suggest - - - name: Run PHPUnit - run: ./vendor/bin/phpunit -c dev/tests/unit/phpunit.xml.dist app/code/Vendor/SampleModule/Test/Unit +In the above example, the test interacts with the Magento system by logging in as an admin user, opening an admin page, +and asserting the expected page title. + +### Data Fixtures + +Magento 2 allows the creation of data fixtures to provide consistent test data for unit tests. Data fixtures are defined +in XML files and can be used to set up test scenarios. + +```xml + + + + my_module_data + + + + value1 + value2 + + + + + ``` -### GitLab Pipelines - -In your .gitlab-ci.yml, add: +In the above example, a fixture named `my_module_data` is defined, which inserts a row into the `table_name` table with +specified column values. -```yaml -stages: - - test +Fixtures can be used within a test using the `loadFixture()` method provided by MTF: -phpunit: - stage: test - image: php:latest - script: - - composer install - - ./vendor/bin/phpunit -c dev/tests/unit/phpunit.xml.dist app/code/Vendor/SampleModule/Test/Unit +```php +public function testMyModuleWithFixture() +{ + $this->loadFixture('my_module_data'); + // Additional test logic using the fixture data +} ``` -## Summary - - +## Conclusion -Unit testing is a vital part of the Magento 2 development process. It helps ensure that your code functions as expected, -which can help reduce bugs and issues in the future. By using PHPUnit, Magento 2 developers can write and run unit tests -to validate their code throughout the development process. \ No newline at end of file +Unit testing plays a crucial role in software development, enabling developers to validate the correctness of individual +units of code. By incorporating unit testing into your PHP and Magento 2 projects, you can increase code quality, reduce +bugs, and improve maintainability. Use this documentation as a guide to get started with unit testing and leverage the +benefits it offers. Happy testing! diff --git a/versions-and-updates.md b/versions-and-updates.md index e69de29..d411be1 100644 --- a/versions-and-updates.md +++ b/versions-and-updates.md @@ -0,0 +1,106 @@ +# Versions and Updates Documentation + +[TOC] + +## Introduction + +This documentation provides an overview of versions and updates in PHP and Magento 2. Understanding how versions and +updates work is essential for developers to maintain and enhance their applications. This document will explain the +concepts of versions and updates, outline how updates are released and applied, and provide guidance on managing +versions and updates effectively. + +## Understanding Versions + +In software development, versions serve as a way to track and identify different iterations of a project. Each version +represents a distinct release that may introduce new features, fix bugs, or address security vulnerabilities. A version +typically consists of a major, minor, and patch number, following the convention "MAJOR.MINOR.PATCH." + +For example, consider a PHP library with version 2.1.0. Here, "2" represents the major version, "1" represents the minor +version, and "0" represents the patch version. A change in the major version indicates significant changes that may +introduce breaking changes or completely new functionality. A change in the minor version signifies the addition of new +features or improvements without breaking existing functionality. A change in the patch version indicates bug fixes, +small enhancements, or security patches with no breaking changes. + +## Updates and Patches + +Updates and patches are essential for maintaining the health and security of your PHP and Magento 2 applications. +Updates typically refer to changes that introduce new features, improvements, and bug fixes. Patches, on the other hand, +address security vulnerabilities or critical bugs without introducing significant changes. + +For instance, when you receive an update or patch for your Magento 2 store, it may include the addition of new payment +gateways, performance optimizations, or bug fixes related to the checkout process. Patches, however, are released to fix +vulnerabilities such as potential security breaches or critical functional issues. + +## Release Channels + +Both PHP and Magento 2 use release channels to categorize and distribute updates. These channels allow developers to +select the desired level of stability and risk for their applications. The common release channels are: + +1. Stable: This channel provides the most stable and tested updates. It is recommended for production environments where + stability is crucial. +2. Beta: Beta releases are pre-release versions designed to gather feedback from the community before a stable release. + These versions may still contain bugs and should not be used in production environments. +3. Development: Development releases are experimental versions that introduce new features but may also have significant + bugs. They are intended for testing purposes only and should not be used in production environments. + +When considering which release channel to use, it is necessary to evaluate the stability requirements of your +application and balance the desire for new features with the risk of potential issues. + +## Applying Updates + +To apply updates and patches efficiently, it is essential to follow a systematic process. Here is a step-by-step guide: + +1. **Backup your application**: Always create a backup of your application and database before applying any updates. + This ensures that you have a restore point in case any issues arise during the update process. + +2. **Review release notes**: Carefully review the release notes for the update or patch you plan to apply. Release notes + contain important information about the changes, including new features, bug fixes, and known issues. It is crucial + to understand the impact of the update on your application and any potential compatibility concerns. + +3. **Test in a staging environment**: Before applying updates to a production environment, it is best practice to test + them in a staging environment that mirrors your production setup. This allows you to identify and resolve any + compatibility or functional issues before affecting your live application. + +4. **Apply update**: Once you are confident the update will not cause unforeseen problems, apply the update to your + production environment or desired target. The exact process for applying updates may vary depending on the specific + platform or framework you are using. + +5. **Verify functionality**: After applying the update, thoroughly test your application to ensure all features are + working as expected. Check critical functionality, run automated tests, and perform real-world scenarios to ensure + the update did not introduce any regressions. + +6. **Monitor for issues**: Keep a close eye on your application after updates are applied. Monitor logs, user feedback, + and performance metrics to identify any new issues that may have been introduced. Timely detection and resolution of + issues are crucial to maintaining a healthy application. + +## Managing Versions + +Managing versions effectively is vital to ensure the stability and security of your PHP and Magento 2 applications. Here +are some best practices for version management: + +1. **Semantic versioning**: Follow semantic versioning conventions to clearly communicate the impact of version changes. + Adhering to this convention helps developers understand the level of change and compatibility implications when + upgrading to a new version. + +2. **Dependency management**: When working with libraries or frameworks that have dependencies, use dependency + management tools like Composer for PHP or Magento's composer.json file for Magento 2. These tools simplify the + process of managing and updating dependencies, ensuring compatibility and avoiding version conflicts. + +3. **Keep up with updates**: Regularly check for updates and patches for your PHP and Magento 2 components, including + libraries, frameworks, and extensions. Staying up to date with the latest releases helps ensure that your application + benefits from new features, performance improvements, and security patches. + +4. **Testing and staging environments**: Maintain dedicated testing and staging environments to validate updates before + deploying them to production. These environments ensure that updates do not introduce unexpected issues that may + disrupt your live application. + +5. **Version control**: Utilize a version control system, such as Git, to track changes and manage different versions of + your application's code. Version control allows you to roll back to previous versions if needed and provides a + history of changes made over time. + +## Conclusion + +Versions and updates play a crucial role in maintaining and enhancing PHP and Magento 2 applications. Understanding the +concepts of versions, release channels, and update management is essential for successful application development and +maintenance. By following best practices, staying informed about updates, and applying updates diligently, you can +ensure the stability, security, and longevity of your applications. diff --git a/view-xml.md b/view-xml.md deleted file mode 100644 index e69de29..0000000 diff --git a/view_xml.md b/view_xml.md new file mode 100644 index 0000000..8db9d65 --- /dev/null +++ b/view_xml.md @@ -0,0 +1,141 @@ +# `view.xml` Reference Documentation + +[TOC] + +The `view.xml` file is an important configuration file in Magento 2 that controls various visual aspects of the +frontend. This documentation will provide an in-depth explanation of the structure and options available in +the `view.xml` file, as well as how to customize it to meet your specific visual requirements. + +## File Location + +The `view.xml` file is typically located in the `app/design/frontend///etc` directory of your Magento 2 +installation. If the file does not exist, you can create it manually. + +## Structure + +The `view.xml` file follows an XML structure and is divided into several sections, each responsible for configuring a +specific visual aspect of the frontend. The main sections include ``, ``, ``, ``, +and ``. Let's explore each section in detail. + +### `` + +The `` section allows you to define and override CSS variables. These variables can be used throughout your theme +to control various CSS properties. Here's an example of how to define a variable: + +```xml + + + red + +``` + +In this example, we define a variable named `customVariable` with the value `red`. This variable can then be used in +your CSS files like this: + +```css +.my-element { + background-color: var(--customVariable); +} +``` + +### `` + +The `` section allows you to define and override color values used in your theme. You can specify colors for +various elements such as text, buttons, links, and more. Here's an example: + +```xml + + + black + blue + +``` + +In this example, we set the base text color to `black` and the primary button color to `blue`. These color values can be +referenced in your CSS using the `@color` directive: + +```css +.my-text { + color: @color text . base; +} +``` + +### `` + +The `` section is used to define image-related configuration. You can specify image sizes, aspect ratios, and +other properties. Here's an example: + +```xml + + + + 1000 + 1000 + + +``` + +In this example, we define an image with the id `product_page_main_image` and set its width and height to `1000`. This +configuration can be used in your theme's templates to control the size of the image. + +### `` + +The `` section allows you to define and override template files used in your theme. You can specify which +template files to use for different elements of the frontend. Here's an example: + +```xml + + + + +``` + +In this example, we specify that the template file `Magento_Catalog::product/list.phtml` should be used and overridden +in our theme. This allows you to customize the appearance and behavior of the product list page according to your +requirements. + +### `` + +The `` section defines the layout configuration for your theme. You can specify the layout files to use for +different pages and blocks. Here's an example: + +```xml + + + + + + +``` + +In this example, we define a layout update with the id `my_custom_layout`. This layout update can be used to modify the +structure and arrangement of blocks on specific pages of your theme. + +## Example + +To illustrate how the `view.xml` file is used, let's take a specific example. Suppose you want to customize the +appearance of the product image on the product detail page. You can achieve this by modifying the `` section of +your `view.xml` file: + +```xml + + + + 800 + 800 + + +``` + +In this example, we set the width and height of the `product_page_main_image` to `800`, which will result in a larger +image size on the product detail page. + +Remember to clear the cache after making changes to the `view.xml` file for the changes to take effect. + +## Conclusion + +The `view.xml` file is a powerful tool for customizing the visual aspects of your Magento 2 frontend. By understanding +its structure and options, you can tailor your theme to meet your specific design requirements. The examples provided in +this documentation should serve as a starting point for your customization efforts. diff --git a/web-api.md b/web-api.md index e69de29..2eb9bc8 100644 --- a/web-api.md +++ b/web-api.md @@ -0,0 +1,115 @@ +# Web API Documentation + +[TOC] + +## Introduction + +Welcome to the Web API documentation for Magento 2! This document aims to provide you with all the necessary information +to interact with Magento's Web API using PHP. + +Magento's Web API allows you to programmatically interact with various resources and perform CRUD (Create, Read, Update, +Delete) operations on them. It provides a secure and standardized way to access and manipulate data within a Magento +installation. + +## Authentication + +Before you can start using the Web API, you need to authenticate your requests. Magento 2 supports token-based +authentication using OAuth. To obtain an access token, you need to follow these steps: + +1. Create an integration in your Magento admin panel. Go to *System* > *Extensions* > *Integrations* and click on *Add + New Integration*. + +2. Fill in the integration details and assign the appropriate permissions to the integration. + +3. Once you have created the integration, Magento will generate a set of consumer key and consumer secret. + +4. To obtain an access token, you need to make a POST request to the `/V1/integration/admin/token` endpoint with the + consumer key and secret as the payload. Here's an example using cURL: + +```bash +curl -X POST \ + 'https://your-magento-installation.com/rest/V1/integration/admin/token' \ + -H 'Content-Type: application/json' \ + -d '{ + "username": "your-username", + "password": "your-password" + }' +``` + +5. The response will be the access token that you can use to authenticate subsequent requests. Make sure to securely + store and handle this token. + +## API Endpoints + +Magento's Web API provides a wide range of endpoints to interact with various resources such as customers, products, +orders, and more. Each endpoint follows a consistent URL structure: + +``` +https://your-magento-installation.com/rest// +``` + +For example, to get a list of all customers, you would make a GET request to `/V1/customers`. Similarly, to create a new +product, you would make a POST request to `/V1/products`. + +## Request and Response Format + +All requests to the Web API should be made using the HTTP protocol, with appropriate HTTP methods such as GET, POST, +PUT, and DELETE, depending on the operation you want to perform. + +The request payloads and response bodies are typically in JSON format. Make sure to set the `Content-Type` header +to `application/json` for requests that have a payload. + +Here's an example of a request to create a new product: + +```php + [ + 'sku' => 'test-product', + 'name' => 'Test Product', + 'price' => 10, + 'status' => 1 + // ... other product attributes + ] +]; + +$ch = curl_init($endpoint); + +curl_setopt($ch, CURLOPT_POST, true); +curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); +curl_setopt($ch, CURLOPT_HTTPHEADER, [ + 'Content-Type: application/json', + 'Authorization: Bearer ' . $accessToken +]); + +$response = curl_exec($ch); + +curl_close($ch); + +// Handle the response as needed +``` + +## Error Handling + +When interacting with the Web API, it's important to handle errors gracefully. If a request fails, the response will +include an appropriate HTTP status code along with an error message in the response body. + +For example, if you make a request to create a new product without providing required attributes, you will receive +a `400 Bad Request` response with an error message indicating the missing attributes. + +Make sure to check the HTTP status code and the response body to handle errors appropriately in your code. + +## Conclusion + +Congratulations! You now have a solid understanding of Magento 2's Web API and how to interact with it using PHP. You +should be able to make requests to various endpoints, authenticate using OAuth, handle errors, and perform CRUD +operations on different resources. + +For more detailed information on specific endpoints and available operations, refer to the official Magento 2 Web API +documentation. + +Happy coding! diff --git a/webapi-xml.md b/webapi-xml.md deleted file mode 100644 index e69de29..0000000 diff --git a/webapi_xml.md b/webapi_xml.md new file mode 100644 index 0000000..2662477 --- /dev/null +++ b/webapi_xml.md @@ -0,0 +1,98 @@ +# `webapi.xml` Reference Documentation + +[TOC] + +## Introduction + +The `webapi.xml` file in Magento 2 is a crucial configuration file that defines the web APIs available in your Magento +installation. This file allows you to control the access and behavior of your web APIs. In this reference documentation, +we will explore the structure and various elements of the `webapi.xml` file, providing you with a comprehensive +understanding of how to utilize and customize web APIs in Magento 2. + +## File Structure + +The `webapi.xml` file is located in the `etc` directory of your Magento module. Its primary purpose is to define the web +APIs associated with that module. The file follows a hierarchical structure comprising of the following key elements: + +1. `routes` +2. `route` +3. `service` +4. `method` + +Now, let's dive deeper into each of these elements and understand their roles in configuring web APIs. + +## Routes + +The `routes` element acts as the root element for defining the web API routes in your module. Under the `routes` +element, you define different routes that correspond to different parts of your module. + +Example: + +```xml + + + + +``` + +## Route + +The `route` element allows you to define a specific route within your module. Each route represents a specific URL +endpoint for accessing the web API. Within the `route` element, you define the services associated with that route. + +Example: + +```xml + + + + +``` + +In the above example, we have defined a route with the URL `/V1` and the HTTP method `GET`. You can have +multiple `route` elements within the `routes` element, each representing a different URL endpoint. + +## Service + +The `service` element represents a specific service or resource in your web API. It defines the URL endpoint for +accessing that service and also contains the methods associated with that service. + +Example: + +```xml + + + + +``` + +In the above example, we have defined a service with the class `Magento\Catalog\Api\ProductRepositoryInterface` and the +method `get`. This service represents the product repository in the catalog API. You can have multiple `service` +elements within a `route` element, each representing a different service or resource. + +## Method + +The `method` element defines a specific method within a service. It represents an individual API endpoint that can be +accessed to perform a specific action. The `method` element contains attributes such as `name` and `entityType` that +further configure the behavior of the method. + +Example: + +```xml + + + + +``` + +In the above example, we have defined a method with the name `get` and +the `entity_type` `Magento\Catalog\Api\Data\ProductInterface`. This method allows you to retrieve product information. +You can have multiple `method` elements within a `service` element, each representing a different method or action. + +## Conclusion + +The `webapi.xml` file is a powerful configuration file that allows you to define and customize web APIs in your Magento +2 module. By understanding the structure and elements of this file, you can effectively configure the behavior and +access controls of your web APIs. Use the provided examples and code snippets as a guide to create your own `webapi.xml` +file and harness the full potential of web APIs in your Magento 2 project. diff --git a/widget-xml.md b/widget-xml.md deleted file mode 100644 index e69de29..0000000 diff --git a/widget_xml.md b/widget_xml.md new file mode 100644 index 0000000..7e547f9 --- /dev/null +++ b/widget_xml.md @@ -0,0 +1,131 @@ +# `widget.xml` Reference Documentation + +[TOC] + +## Overview + +The `widget.xml` file is an important configuration file in Magento 2 that defines the behavior and properties of +widgets. Widgets are reusable components that can be placed in various areas of a Magento store to display dynamic +content. This reference documentation will provide a detailed explanation of the `widget.xml` file and its various +elements. + +## XML Structure + +The `widget.xml` file follows a structured XML format. It consists of a root `` element, which contains one or +more `` elements. Each `` element represents a specific widget and contains its configuration details. +Let's examine the key elements and attributes of the `widget.xml` file. + +## `` Element + +The `` element is the main building block of the `widget.xml` file. It defines a widget and its properties. Here +is an example: + +```xml + + + + This is an example widget. + + + + + + + + + + + + + +``` + +Let's break down the attributes and child elements of the `` element: + +- `id` (required): An identifier for the widget. It should be unique within the scope of the module. +- `class` (required): The fully qualified class name of the widget block. +- `