### Example Store Configuration Parameters Source: https://github.com/mage-os/devdocs/blob/main/installation-guide.md This is an example of how to specify language, currency, and timezone during installation. ```shell --language=en_US \ --currency=USD \ --timezone=America/New_York ``` -------------------------------- ### Configure OpenSearch for Installation Source: https://github.com/mage-os/devdocs/blob/main/installation-guide.md Add these parameters to the setup:install command if you have OpenSearch installed. Replace placeholders with your OpenSearch details. ```shell --search-engine=opensearch \ --opensearch-host=OPENSEARCH_HOST \ --opensearch-port=OPENSEARCH_PORT \ --opensearch-index-prefix=OPENSEARCH_INDEX_PREFIX \ --opensearch-timeout=15 ``` -------------------------------- ### Configure Base Store Settings During Installation Source: https://github.com/mage-os/devdocs/blob/main/installation-guide.md Add these parameters to the setup:install command to set initial store configurations like language, currency, and timezone. ```shell --language=languageCode_countryCode \ --currency=CURRENCY \ --timezone=TIMEZONE ``` -------------------------------- ### Configure Elasticsearch for Installation Source: https://github.com/mage-os/devdocs/blob/main/installation-guide.md Add these parameters to the setup:install command if you have Elasticsearch installed. Replace placeholders with your Elasticsearch host and port. ```shell --search-engine=elasticsearch7 \ --elasticsearch-host=ELASTICSEARCH_HOST \ --elasticsearch-port=ELASTICSEARCH_PORT ``` -------------------------------- ### Create Admin User During Installation Source: https://github.com/mage-os/devdocs/blob/main/installation-guide.md Include these parameters in the setup:install command to create an administrator account. Provide your desired admin details. ```shell --admin-firstname=ADMIN_FIRSTNAME \ --admin-lastname=ADMIN_LASTNAME \ --admin-email=ADMIN_EMAIL \ --admin-user=ADMIN_USER \ --admin-password=ADMIN_PASSWORD ``` -------------------------------- ### Implement Database Schema Installation Source: https://github.com/mage-os/devdocs/blob/main/best-practices-for-extension-development.md Create an InstallSchema.php file to handle database setup and versioning. This file contains the logic for creating or updating the database schema. ```php startSetup(); // Add database schema setup logic here $installer->endSetup(); } } ``` -------------------------------- ### Configure Redis for Caching and Sessions Source: https://github.com/mage-os/devdocs/blob/main/installation-guide.md Additional parameters for the `setup:install` command to configure Redis for session storage, general caching, and full-page caching. ```shell --session-save=redis \ --session-save-redis-host=REDIS_HOST \ --session-save-redis-port=REDIS_PORT \ --session-save-redis-db=0 \ --session-save-redis-max-concurrency=20 \ --cache-backend=redis \ --cache-backend-redis-server=REDIS_HOST \ --cache-backend-redis-port=REDIS_PORT \ --cache-backend-redis-db=1 \ --page-cache=redis \ --page-cache-redis-server=REDIS_HOST \ --page-cache-redis-port=REDIS_PORT \ --page-cache-redis-db=2 ``` -------------------------------- ### Configure RabbitMQ for Asynchronous Processes Source: https://github.com/mage-os/devdocs/blob/main/installation-guide.md Additional parameters for the `setup:install` command to configure RabbitMQ for handling asynchronous tasks. ```shell --amqp-host=RABBIT_MQ_HOST \ --amqp-port=RABBIT_MQ_PORT \ --amqp-user=RABBIT_MQ_USER \ --amqp-password=RABBIT_MQ_PASSWORD ``` -------------------------------- ### Create Product Example Source: https://github.com/mage-os/devdocs/blob/main/web-api.md An example demonstrating how to make a POST request to create a new product using the Magento Web API with PHP and cURL. ```APIDOC ## Create Product ### Description This example demonstrates how to create a new product via the Web API. It includes setting up the request with an access token and sending product data in JSON format. ### Method POST ### Endpoint `/V1/products` ### Request Body - **product** (object) - Required - An object containing the product details. - **sku** (string) - Required - The stock keeping unit for the product. - **name** (string) - Required - The name of the product. - **price** (float) - Required - The price of the product. - **status** (integer) - Required - The status of the product (e.g., 1 for enabled). - ... other product attributes ### Request Example ```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 ?> ``` ### Response #### Success Response (200) - **sku** (string) - The SKU of the created product. - **id** (integer) - The ID of the created product. - ... other product details ``` -------------------------------- ### Install Magento 2 Application Source: https://github.com/mage-os/devdocs/blob/main/installation-guide.md Installs the Magento 2 application with various configurations for database, search engine, caching, and session storage. Ensure all parameters match your Warden setup. ```shell bin/magento setup:install \ --backend-frontname=backend \ --amqp-host=rabbitmq \ --amqp-port=5672 \ --amqp-user=guest \ --amqp-password=guest \ --db-host=db \ --db-name=magento \ --db-user=magento \ --db-password=magento \ --search-engine=opensearch \ --opensearch-host=opensearch \ --opensearch-port=9200 \ --opensearch-index-prefix=magento2 \ --opensearch-enable-auth=0 \ --opensearch-timeout=15 \ --http-cache-hosts=varnish:80 \ --session-save=redis \ --session-save-redis-host=redis \ --session-save-redis-port=6379 \ --session-save-redis-db=2 \ --session-save-redis-max-concurrency=20 \ --cache-backend=redis \ --cache-backend-redis-server=redis \ --cache-backend-redis-db=0 \ --cache-backend-redis-port=6379 \ --page-cache=redis \ --page-cache-redis-server=redis \ --page-cache-redis-db=1 \ --page-cache-redis-port=6379 ``` -------------------------------- ### Magento 2 API Endpoint Examples Source: https://github.com/mage-os/devdocs/blob/main/how-to-use-and-extend-apis.md Examples of common Magento 2 API endpoints for interacting with the 'products' resource. Use GET for retrieval, POST for creation, PUT for updates, and DELETE for removal. ```http GET https://example.com/rest/V1/products ``` ```http GET https://example.com/rest/V1/products/10 ``` ```http POST https://example.com/rest/V1/products ``` ```http PUT https://example.com/rest/V1/products/10 ``` ```http DELETE https://example.com/rest/V1/products/10 ``` -------------------------------- ### Example: Enable Product Attribute Indexer Source: https://github.com/mage-os/devdocs/blob/main/indexers.md Demonstrates how to enable the product attribute indexer by setting its mode to 'update'. ```bash bin/magento indexer:set-mode catalog_product_attribute update ``` -------------------------------- ### Install MySQL Database Server Source: https://github.com/mage-os/devdocs/blob/main/server-setup-and-configuration.md Installs the MySQL server. You will be prompted to set a strong root password during installation. Ensure you are using MySQL 8.0 or later. ```bash $ sudo apt update $ sudo apt install mysql-server ``` -------------------------------- ### Upgrade Magento Setup Source: https://github.com/mage-os/devdocs/blob/main/cli-commands.md Applies database schema and data updates after installing or updating modules. Run this command to ensure your Magento instance is up-to-date. ```bash php bin/magento setup:upgrade ``` -------------------------------- ### Install Apache Web Server Source: https://github.com/mage-os/devdocs/blob/main/server-setup-and-configuration.md Installs Apache and enables essential modules for web serving. Ensure your system's package manager is updated before running. ```bash $ sudo apt update $ sudo apt install apache2 $ a2enmod rewrite headers ssl expires brotli ``` -------------------------------- ### Example Unit Test Output Source: https://github.com/mage-os/devdocs/blob/main/unit-testing.md This is an example of the output you might see after successfully running unit tests. ```text PHPUnit X.X.X by Sebastian Bergmann and contributors. . 1 / 1 (100%) Time: X ms, Memory: X MB OK (1 test, 1 assertion) ``` -------------------------------- ### Example: Reindex Product Attribute Indexer Source: https://github.com/mage-os/devdocs/blob/main/indexers.md Demonstrates how to manually reindex the product attribute indexer. ```bash bin/magento indexer:reindex catalog_product_attribute ``` -------------------------------- ### RequireJS Configuration Example with Paths and Shims Source: https://github.com/mage-os/devdocs/blob/main/requirejs.md Configure module paths and define shims for non-AMD modules. This example sets a base URL and maps CDN paths for jQuery and Lodash. ```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: '_' } } }); ``` -------------------------------- ### Magento 2 Plugin Example Source: https://github.com/mage-os/devdocs/blob/main/overview-of-magento-2-development.md Demonstrates a plugin class with methods for before, after, and around method execution. ```php / / etc/ module.xml registration.php ``` -------------------------------- ### Creating a Customer Source: https://github.com/mage-os/devdocs/blob/main/graphql-apis.md Example of how to use a mutation to create a new customer with provided details. ```APIDOC ## 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`. ``` -------------------------------- ### Install Mage-OS/Magento with Database and Services Source: https://github.com/mage-os/devdocs/blob/main/installation-guide.md Core command to install Mage-OS or Magento, configuring database connection, base URLs, backend frontname, and enabling secure connections. It also sets up Elasticsearch, RabbitMQ, and Redis for caching and sessions. ```shell bin/magento setup:install \ --db-host=DATABASE_HOST \ --db-name=DATABASE_NAME \ --db-user=DATABASE_USER \ --db-password=DATABASE_PASSWORD \ --base-url=https://www.example.com/ \ --base-url-secure=https://www.example.com/ \ --backend-frontname=BACKEND_FRONTNAME \ --use-secure=1 \ --use-secure-admin=1 \ --use-rewrites=1 ``` -------------------------------- ### Configure Composer for Magento Marketplace Source: https://github.com/mage-os/devdocs/blob/main/installation-guide.md Example JSON configuration for Composer to add repo.magento.com, enabling installation of Marketplace packages alongside Mage-OS or mirror repositories. ```json "repositories": { "mage-os": { "type": "composer", "url": "https://repo.mage-os.org/" }, "magento-marketplace": { "type": "composer", "url": "https://repo.magento.com", "only": [ "vendorC/module-d", "vendorE/*" ] }, }, ``` -------------------------------- ### Magento 2 Observer Example Source: https://github.com/mage-os/devdocs/blob/main/overview-of-magento-2-development.md An example of an observer class that listens to an event and performs custom logic. ```php getData('product'); // Perform custom logic } } ``` -------------------------------- ### Install Composer Dependencies Source: https://github.com/mage-os/devdocs/blob/main/how-to-contribute-to-the-magento-2-community.md Install necessary testing dependencies using Composer before running tests. ```shell composer install ``` -------------------------------- ### Implement Custom Method in Model Source: https://github.com/mage-os/devdocs/blob/main/how-to-use-and-extend-apis.md Provide the concrete implementation for your custom API method. This example delegates to the original repository's get method after custom logic. ```php productRepository = $productRepository; } public function getBySku($sku) { // Implement your custom logic here return $this->productRepository->get($sku); } // Implement other methods from the original interface } ``` -------------------------------- ### Initialize Magento Framework Bootstrap Source: https://github.com/mage-os/devdocs/blob/main/brief-explanation-of-each-component.md Use this to bootstrap the Magento application and get the Object Manager for accessing services. ```php use Magento\Framework\App\Bootstrap; require __DIR__ . '/app/bootstrap.php'; $bootstrap = Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); ``` -------------------------------- ### API Endpoints Examples Source: https://github.com/mage-os/devdocs/blob/main/how-to-use-and-extend-apis.md Illustrates common API endpoints for interacting with products in Magento 2. ```APIDOC ## API Endpoints Examples ### Description These examples demonstrate how to use different HTTP methods to interact with the products resource via the Magento 2 API. ### GET /rest/V1/products Retrieves a collection of products. ### GET /rest/V1/products/{id} Retrieves a specific product by its ID. ### POST /rest/V1/products Creates a new product. ### PUT /rest/V1/products/{id} Updates an existing product by its ID. ### DELETE /rest/V1/products/{id} Deletes a specific product by its ID. ``` -------------------------------- ### Magento 2 Extension Directory Structure Source: https://github.com/mage-os/devdocs/blob/main/developing-extensions-in-magento-2.md Example structure for a basic Magento 2 extension named 'MyExtension'. ```text MyExtension/ ├── etc/ │ ├── module.xml │ └── ... ├── Block/ │ ├── MyBlock.php │ └── ... ├── Controller/ │ ├── Index/ │ │ └── Index.php │ └── ... ├── Model/ │ ├── MyModel.php │ └── ... ├── view/ │ └── frontend/ │ │ ├── layout/ │ │ │ ├── myextension_index_index.xml │ │ │ └── ... │ │ ├── templates/ │ │ │ ├── myextension.phtml │ │ │ └── ... │ └── ... └── ... ``` -------------------------------- ### Verify PHPUnit Installation Source: https://github.com/mage-os/devdocs/blob/main/unit-testing.md Check the installed PHPUnit version to confirm the installation was successful. ```bash phpunit --version ``` -------------------------------- ### Authentication Example Source: https://github.com/mage-os/devdocs/blob/main/how-to-use-and-extend-apis.md Demonstrates how to authenticate API requests using a bearer token with cURL. ```APIDOC ## Authentication Example ### Description This example shows how to authenticate your API requests using a bearer token. Replace `YOUR_TOKEN` with your actual authentication token. ### Method GET ### Endpoint `https://example.com/rest/V1/products` ### Request Headers - `Authorization`: `Bearer YOUR_TOKEN` ``` -------------------------------- ### Querying Products Source: https://github.com/mage-os/devdocs/blob/main/graphql-apis.md Example of how to query a list of products and retrieve specific fields like ID, name, and price. ```APIDOC ## 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. ``` -------------------------------- ### Sass SCSS Syntax Example Source: https://github.com/mage-os/devdocs/blob/main/css-preprocessing.md A basic example of SCSS syntax, which is a superset of CSS. It demonstrates variable usage and basic styling. ```scss $primary-color: #007bff; .button { padding: 10px; background-color: $primary-color; color: white; } ``` -------------------------------- ### Reindex and Flush Cache Source: https://github.com/mage-os/devdocs/blob/main/installation-guide.md Execute these commands after installation to ensure all indexes are up-to-date and the cache is cleared. ```shell bin/magento indexer:reindex bin/magento cache:flush ``` -------------------------------- ### Example Cron Job Entry Source: https://github.com/mage-os/devdocs/blob/main/installation-guide.md This is an example of what the Mage-OS cron job entry might look like in your server's crontab. ```shell #~ MAGENTO START 69dd2b02e1f3a65918182048ea4e29979a849d8942e8f53ed20a4bf10e529b36 * * * * * /usr/bin/php /var/www/html/bin/magento cron:run 2>&1 | grep -v "Ran jobs by schedule" >> /var/www/html/var/log/magento.cron.log #~ MAGENTO END 69dd2b02e1f3a65918182048ea4e29979a849d8942e8f53ed20a4bf10e529b36 ``` -------------------------------- ### Install PHPUnit Globally Source: https://github.com/mage-os/devdocs/blob/main/unit-testing.md Install PHPUnit globally using Composer. This command ensures PHPUnit is available system-wide for your projects. ```bash composer global require phpunit/phpunit ``` -------------------------------- ### Install Missing PHP XSL Extension Source: https://github.com/mage-os/devdocs/blob/main/troubleshooting-common-installation-issues.md Install the PHP XSL extension using apt-get on Ubuntu to resolve errors related to its absence. ```bash sudo apt-get install php-xsl ``` -------------------------------- ### Authentication Header Example Source: https://github.com/mage-os/devdocs/blob/main/graphql-apis.md Shows how to include an access token in the `Authorization` header for API requests. ```APIDOC ## Getting Started 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 ``` ``` -------------------------------- ### Verify Cron Job Installation Source: https://github.com/mage-os/devdocs/blob/main/installation-guide.md After running `cron:install`, use this command to view your server's crontab and confirm the Mage-OS cron job entry. ```shell crontab -l ``` -------------------------------- ### Install Codeception using Composer Source: https://github.com/mage-os/devdocs/blob/main/testing-tools.md Add Codeception as a development dependency to your project using Composer. ```shell composer require --dev codeception/codeception ``` -------------------------------- ### Display Recent Products in Template Source: https://github.com/mage-os/devdocs/blob/main/layouts-blocks-and-templates.md Example of accessing block data and iterating through products in a template file. ```php getRecentProducts(); foreach ($recentProducts as $product) { // Display product details } ``` -------------------------------- ### Database Schema Setup Source: https://github.com/mage-os/devdocs/blob/main/module-development.md Defines how to create and manage database tables using declarative schema in Magento 2 modules. ```APIDOC ## Database Schema Setup To create a declarative schema script, follow these steps: 1. Create a file named `db_schema.xml` inside your module's `etc` directory. 2. Implement the necessary logic inside the file. Here's an example: ```xml
``` 3. Run the whitelist generation command: ```shell bin/magento setup:db-declaration:generate-whitelist --module-name=Vendor_Module ``` 4. Run the setup upgrade command to apply your schema changes: ```shell bin/magento setup:upgrade ``` ``` -------------------------------- ### Mock API Requests with MSW Source: https://github.com/mage-os/devdocs/blob/main/javascript-testing.md Use msw (Mock Service Worker) to mock API requests in your integration tests. This example demonstrates setting up a server to intercept GET requests to '/api/data' and return a JSON response. Ensure the server is started before tests and reset after each test. ```javascript 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'}); }); }); ``` -------------------------------- ### Set Up a PHP SOAP Client Source: https://github.com/mage-os/devdocs/blob/main/soap-apis.md Instantiate a SoapClient in PHP. Configure options like tracing for debugging. Ensure the WSDL URL is correct. ```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); ``` -------------------------------- ### Magento 2 Layout XML Example Source: https://github.com/mage-os/devdocs/blob/main/magento-2-coding-standards.md Defines page structure by referencing a block and template in a layout XML file. ```xml ``` -------------------------------- ### Make a GET Request to a REST API using Guzzle Source: https://github.com/mage-os/devdocs/blob/main/rest-apis-soap-apis.md Use Guzzle to make a GET request to a REST API endpoint. Ensure Guzzle is installed and imported. ```php use GuzzleHttp\Client; $client = new Client(); $response = $client->get('https://api.example.com/users'); $body = $response->getBody(); $data = json_decode($body, true); ``` -------------------------------- ### REST API: Get User Information Example Source: https://github.com/mage-os/devdocs/blob/main/rest-apis-soap-apis.md This snippet demonstrates how to make a GET request to a REST API endpoint to retrieve user information using Guzzle in PHP. ```APIDOC ## GET /api/users/{id} ### Description Retrieves information for a specific user based on their ID. ### Method GET ### Endpoint `/api/users/{id}` ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the user to retrieve. ### Request Example ```php use GuzzleHttp\Client; $client = new Client(); $id = 123; $response = $client->get('https://api.example.com/users/' . $id); $data = json_decode($response->getBody(), true); ``` ### Response #### Success Response (200) - **id** (integer) - The user's unique identifier. - **name** (string) - The user's full name. - **email** (string) - The user's email address. #### Response Example ```json { "id": 123, "name": "John Doe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### List Currencies Source: https://github.com/mage-os/devdocs/blob/main/cli-commands.md Displays a list of available currencies in your Magento installation. Useful for multi-currency setups. ```bash php bin/magento info:currency:list ``` -------------------------------- ### Make GET Request with Guzzle Source: https://github.com/mage-os/devdocs/blob/main/api-reference.md Example of making a GET request to retrieve customer details using the Guzzle HTTP client library in PHP. Requires the GuzzleHttp client and an access token. ```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']; ``` -------------------------------- ### Add Theme Preview Image (theme.xml) Source: https://github.com/mage-os/devdocs/blob/main/theme-development.md Specifies a preview image for the theme. The image path is relative to the theme's directory. Ensure the file exists before running setup:upgrade. ```xml MyTheme Magento/blank media/preview.jpg ``` -------------------------------- ### Get Indexer Information Source: https://github.com/mage-os/devdocs/blob/main/cli-commands.md Provides information about the indexers in your Magento 2 installation. Useful for understanding indexer status and types. ```bash php bin/magento indexer:info ``` -------------------------------- ### Retrieve Order Details (API Endpoint) Source: https://github.com/mage-os/devdocs/blob/main/api-reference.md Example of a GET request to retrieve order details using the Orders API endpoint. ```http GET /rest/V1/orders/{orderId} ``` -------------------------------- ### Data Source Configuration Example Source: https://github.com/mage-os/devdocs/blob/main/indexer.md Illustrates how to configure a data source within an indexer.xml file. The 'name' attribute should correspond to the data source name used elsewhere in the configuration. ```xml ``` -------------------------------- ### Retrieve Customer Details (API Endpoint) Source: https://github.com/mage-os/devdocs/blob/main/api-reference.md Example of a GET request to retrieve customer details using the Customers API endpoint. ```http GET /rest/V1/customers/{customerId} ``` -------------------------------- ### Creating a New Product Source: https://github.com/mage-os/devdocs/blob/main/rest-apis.md Demonstrates how to create a new product by making a POST request to the /products endpoint with product data in the request body. ```APIDOC ## POST /products ### Description Creates a new product in the Magento 2 system. ### Method POST ### Endpoint /rest/V1/products ### Request Body - **sku** (string) - Required - The SKU of the product. - **name** (string) - Required - The name of the product. - **price** (number) - Required - The price of the product. ### Request Example ```json { "sku": "new-product", "name": "New Product", "price": 9.99 // Additional product data } ``` ### Response #### Success Response (200) Details of the newly created product. #### Response Example ```json { "id": 1, "sku": "new-product", "name": "New Product", "price": 9.99 } ``` ``` -------------------------------- ### SOAP API: Get User Information Example Source: https://github.com/mage-os/devdocs/blob/main/rest-apis-soap-apis.md This snippet demonstrates how to call a SOAP API method to retrieve user information using the SoapClient in PHP. ```APIDOC ## SOAP Method: getUserInfo ### Description Retrieves user information by making a call to the `getUserInfo` SOAP method. ### Method SOAP Call ### Parameters #### Request Parameters - **id** (integer) - Required - The ID of the user to retrieve. ### Request Example ```php $wsdl = 'https://api.example.com/soap?wsdl'; $soapClient = new SoapClient($wsdl); $response = $soapClient->getUserInfo(['id' => 123]); ``` ### Response #### Success Response - **getUserInfoResult** (object) - Contains the user details. - **id** (integer) - The user's unique identifier. - **name** (string) - The user's full name. - **email** (string) - The user's email address. #### Response Example (XML) ```xml 123 John Doe john.doe@example.com ``` ``` -------------------------------- ### Define Extension Configuration with system.xml Source: https://github.com/mage-os/devdocs/blob/main/best-practices-for-extension-development.md Use system.xml to define configuration fields and sections for the admin panel. This example shows how to create a tab, a section, and a group with a select field. ```xml
acme Acme_FastPay::config Magento\Config\Model\Config\Source\Yesno
``` -------------------------------- ### Install PHP 8.2 and Extensions Source: https://github.com/mage-os/devdocs/blob/main/server-setup-and-configuration.md Installs PHP 8.2 along with a comprehensive list of extensions required for Magento 2. After installation, configure php.ini. ```bash $ sudo apt update $ sudo apt install php8.2 php8.2-apcu php8.2-amqp php8.2-bcmath php8.2-bz2 php8.2-cli php8.2-common php8.2-curl php8.2-dba php8.2-fpm php8.2-gd php8.2-igbinary php8.2-imagick php8.2-imap php8.2-intl php8.2-mbstring php8.2-memcached php8.2-msgpack php8.2-mysql php8.2-opcache php8.2-phpdbg php8.2-redis php8.2-soap php8.2-sqlite3 php8.2-xml php8.2-zip ``` -------------------------------- ### Full ACL Structure with Resources, Roles, and Permissions Source: https://github.com/mage-os/devdocs/blob/main/acl.md Provides a comprehensive example of acl.xml, showing nested resources, roles, and the application of permissions. ```xml ``` -------------------------------- ### Magento 2 Project File Structure Source: https://github.com/mage-os/devdocs/blob/main/magento-2-coding-standards.md Illustrates the recommended directory structure for a Magento 2 project. ```text app/ code/ / / Block/ Controller/ etc/ Helper/ Model/ Setup/ view/ adminhtml/ frontend/ design/ adminhtml/ frontend/ lib/ ``` -------------------------------- ### Create Customer using Service Contracts (PHP) Source: https://github.com/mage-os/devdocs/blob/main/overview-of-magento-2-apis.md This example demonstrates how to create a new customer in Magento 2 using the `CustomerRepositoryInterface` and `CustomerInterfaceFactory`. It requires proper dependency injection for the repository and factory. ```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; } } ``` -------------------------------- ### Mocha Test Example Source: https://github.com/mage-os/devdocs/blob/main/javascript-testing.md An example of a test written using the Mocha framework, utilizing the built-in assert module. ```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); }); }); }); ``` -------------------------------- ### Configure Magento 2 Page Layout Source: https://github.com/mage-os/devdocs/blob/main/overview-of-magento-2-development.md An example of a Magento 2 layout file. It demonstrates how to remove existing elements (like SKU) and move others (like reviews) within the product page structure. ```xml ``` -------------------------------- ### Magento 2 Plugin Method Interception Source: https://github.com/mage-os/devdocs/blob/main/glossary-of-terms.md Example of a Magento 2 plugin class intercepting a method. This example shows a `before` plugin. ```php class MyPlugin { public function beforeGetName(\Magento\Catalog\Model\Product $product) { return ['My custom name']; } } ``` -------------------------------- ### Initialize Warden Environment Source: https://github.com/mage-os/devdocs/blob/main/installation-guide.md Use this command to create a new Warden environment for your project. Replace YOUR_PROJECTNAME with your desired project name. ```shell warden env-init YOUR_PROJECTNAME magento2 ``` -------------------------------- ### Start Message Queue Consumers Source: https://github.com/mage-os/devdocs/blob/main/cli-commands.md Manually starts the processing of messages by message queue consumers. Use this to ensure background tasks are running. ```bash php bin/magento queue:consumers:start ``` -------------------------------- ### Full Custom Indexer Configuration Source: https://github.com/mage-os/devdocs/blob/main/indexer.md Provides a comprehensive example of a custom indexer configuration, including its title, description, model, ID, status, and dependencies on other indexers. ```xml 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 ``` -------------------------------- ### Implement Accessory Model Source: https://github.com/mage-os/devdocs/blob/main/how-to-add-your-own-products-links-providers.md Provides data from the database for accessory products. It includes methods to retrieve accessory products and their IDs. ```php linkInstance = $productLink; } /** * Retrieve link instance * * @return Product\Link */ public function getLinkInstance() { return $this->linkInstance; } /** * Retrieve array of Accessory products * * @param Product $currentProduct * @return array */ public function getAccessoryProducts(Product $currentProduct) { if (!$this->hasAccessoryProducts()) { $products = []; $collection = $this->getAccessoryProductCollection($currentProduct); foreach ($collection as $product) { $products[] = $product; } $this->setAccessoryProducts($products); } return $this->getData('accessory_products'); } /** * Retrieve accessory products identifiers * * @param Product $currentProduct * @return array */ public function getAccessoryProductIds(Product $currentProduct) { if (!$this->hasAccessoryProductIds()) { $ids = []; foreach ($this->getAccessoryProducts($currentProduct) as $product) { $ids[] = $product->getId(); } $this->setAccessoryProductIds($ids); } return $this->getData('accessory_product_ids'); } /** * Retrieve collection accessory product * * @param Product $currentProduct ``` -------------------------------- ### Sass Indented Syntax Example Source: https://github.com/mage-os/devdocs/blob/main/css-preprocessing.md An example of Sass's indented syntax (Sass). It uses indentation to define structure and a more concise syntax compared to SCSS. ```sass $primary-color: #007bff .button padding: 10px background-color: $primary-color color: white ``` -------------------------------- ### Make GET Request with cURL in PHP Source: https://github.com/mage-os/devdocs/blob/main/rest-apis.md Use this snippet to make a GET request to a REST API endpoint. Ensure the `CURLOPT_RETURNTRANSFER` option is set to receive the response as a string. ```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 } ``` -------------------------------- ### CSS Preprocessing Modularity Example (SCSS) Source: https://github.com/mage-os/devdocs/blob/main/css-preprocessing.md Shows how to structure CSS preprocessing using modular files in SCSS. Styles can be split into multiple files and imported into a master file. ```scss // base.scss $primary-color: #007bff; .button { padding: 10px; background-color: $primary-color; color: white; } // main.scss @import 'base'; .container { ... } ``` -------------------------------- ### Create New Product (API Endpoint) Source: https://github.com/mage-os/devdocs/blob/main/api-reference.md Example of a POST request to create a new product using the Products API endpoint. ```http POST /rest/V1/products ``` -------------------------------- ### PHPUnit Error Example: Unable to Connect to MySQL Source: https://github.com/mage-os/devdocs/blob/main/integration-testing.md This is an example of a PDOException that occurs when the PHP interpreter cannot connect to the test database, often due to incorrect host configuration or network issues between the host and the database server. ```bash phpunit Expected log exception 'PDOException' with message 'SQLSTATE[HY000] [2002] No such file or directory' in /var/www/magento2/vendor/magento/zendframework1/library/Zend/Db/Adapter/Pdo/Abstract.php:129 ``` -------------------------------- ### Define Configuration Section with Group Source: https://github.com/mage-os/devdocs/blob/main/system_xml.md Example of defining a configuration section with a label, tab, resource, and an associated group. Attributes control visibility and sorting. ```xml
my_custom_tab Vendor_Module::config_general
``` -------------------------------- ### PHPUnit Magento 2 Test Case Example Source: https://github.com/mage-os/devdocs/blob/main/functional-testing.md Example of a functional test case written in PHP for Magento 2 using PHPUnit. It demonstrates navigating to a product page, adding the product to the cart, and asserting its presence in the cart. ```php 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'); } ``` -------------------------------- ### Less CSS Preprocessor Example Source: https://github.com/mage-os/devdocs/blob/main/css-preprocessing.md Demonstrates the syntax of Less, a popular CSS preprocessor. It shows the use of variables and basic styling, resembling traditional CSS. ```less @primary-color: #007bff; .button { padding: 10px; background-color: @primary-color; color: white; } ``` -------------------------------- ### Spin Up Warden Environment Source: https://github.com/mage-os/devdocs/blob/main/installation-guide.md Starts all the necessary services for your Warden environment. ```shell warden env up ``` -------------------------------- ### CSS Preprocessing Mixins Example (SCSS) Source: https://github.com/mage-os/devdocs/blob/main/css-preprocessing.md Shows how to define and use mixins in SCSS for reusable blocks of styles. This reduces code duplication and improves organization. ```scss $primary-color: #007bff; @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; } ``` -------------------------------- ### Before Plugin Example in PHP Source: https://github.com/mage-os/devdocs/blob/main/plugins.md Use a 'before' plugin to modify input parameters before a target method executes. Ensure all modified parameters are returned in an array. ```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]; } } ``` -------------------------------- ### Error Response Example Source: https://github.com/mage-os/devdocs/blob/main/graphql-apis.md Illustrates a typical error response structure from the GraphQL API. ```APIDOC ## 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. ``` -------------------------------- ### Create a Unit Test Class Source: https://github.com/mage-os/devdocs/blob/main/best-practices-for-extension-development.md Example of a basic unit test class structure for a Magento 2 extension. Ensure test classes are namespaced correctly under Test\Unit. ```php objectManager = new ObjectManager($this); $this->payment = $this->objectManager->getObject( Payment::class, [ // Inject dependencies here ] ); } public function testExample() { // Write your unit tests here } } ```