### General Command Examples Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/cli-commands/naming-guidelines.md Illustrates basic command structures with only a group and an action, such as setup or module operations. ```bash bin/magento setup:install bin/magento module:status ``` -------------------------------- ### Enable Dry Run Mode for Installation Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/components/declarative-schema/migration-scripts.md Run the setup:install command with the `--dry-run=1` flag to simulate the installation process without making any database changes. This helps in examining generated DDL SQL statements. ```bash bin/magento setup:install --dry-run=1 ``` -------------------------------- ### Install and Recompile Magento Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/components/add-admin-grid.md Run Magento setup upgrade and set the production mode after copying the extension files. ```bash bin/magento setup:upgrade bin/magento deploy:mode:set production ``` -------------------------------- ### Start and End Setup Execution Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/tutorials/admin/custom-text-field-attribute.md Wrap attribute creation code within startSetup() and endSetup() to ensure smooth execution and proper handling of database operations. ```php $this->moduleDataSetup->getConnection()->startSetup(); /* Attribute creation code must be run between these two lines to ensure that the attribute is created smoothly. */ $this->moduleDataSetup->getConnection()->endSetup(); ``` -------------------------------- ### Implement Data Installation Class Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/prepare/extension-lifecycle.md Use the `InstallDataInterface` to create a class that populates the database with initial data during module installation. This runs only on the initial install. ```php moduleDataSetup->getConnection()->startSetup(); /* Attribute creation code must be run between these two lines to ensure that the attribute is created smoothly. */ $this->moduleDataSetup->getConnection()->endSetup(); ``` -------------------------------- ### Clone and Start Code Server Source: https://github.com/adobedocs/commerce-php/blob/main/README.md Clones the adp-devsite repository and starts the code server for local development. This is one of the three required servers for local setup. ```bash git clone https://github.com/AdobeDocs/adp-devsite cd adp-devsite npm install npm run dev ``` -------------------------------- ### Example Library Registration Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/build/component-registration.md This is an example of registering the Magento framework library. ```php use Magento\nFramework\nComponent\nComponentRegistrar; ComponentRegistrar::register(ComponentRegistrar::LIBRARY, 'magento/framework', __DIR__); ``` -------------------------------- ### Implement HttpGetActionInterface Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/components/routing.md This example shows how to implement the `HttpGetActionInterface` to handle GET requests. It demonstrates forwarding the request to a default 'no route' action using `ForwardFactory`. ```php forwardFactory = $forwardFactory; } /** * @inheritdoc */ public function execute() { /** @var Forward $forward */ $forward = $this->forwardFactory->create(); return $forward->forward('defaultNoRoute'); } } ``` -------------------------------- ### Start Content Server Source: https://github.com/adobedocs/commerce-php/blob/main/README.md Starts the content server for local development. Ensure this server is running before proceeding. ```bash npm run dev ``` -------------------------------- ### Clone Admin Grid Example Extension Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/components/add-admin-grid.md Clone the repository to get the complete extension code. ```bash git clone https://github.com/goivvy/admin-grid-tutorial.git ``` -------------------------------- ### Install and Configure Module Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/tutorials/admin/create-admin-page.md Commands to install, enable, and configure the custom module in Adobe Commerce. ```bash bin/magento module:status bin/magento module:enable MyCompany_ExampleAdminNewPage bin/magento setup:upgrade bin/magento setup:di:compile bin/magento setup:static-content:deploy bin/magento cache:clean ``` -------------------------------- ### Clone and Start Runtime Connector Source: https://github.com/adobedocs/commerce-php/blob/main/README.md Clones the devsite-runtime-connector repository and starts the runtime connector server. This is the third required server for local development. ```bash git clone https://github.com/aemsites/devsite-runtime-connector cd devsite-runtime-connector npm install npm run dev ``` -------------------------------- ### Install Swoole Extension Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/components/app-server.md Use this command to install the Swoole extension for PHP. ```bash pecl install swoole ``` -------------------------------- ### Example MinimalDeliveryCostAlgorithm Implementation Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/framework/inventory-management/source-selection-algorithms.md An example class implementing `SourceSelectionInterface` to define a 'Minimal Delivery Cost' algorithm. The `execute` method is a placeholder for the actual logic. ```php namespace Some\Vendor\Namespace\SourceSelection; /** * Minimal Delivery Cost for Merchant algorithm * * @api */ class MinimalDeliveryCostAlgorithm implements SourceSelectionInterface { public function execute( InventoryRequestInterface $inventoryRequest ): SourceSelectionResultInterface; { // TODO: Implement execute() method. } } ``` -------------------------------- ### Example Log Output (Verbose) Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/module-reference/module-application-performance-monitor.md This is an example of the performance metrics logged when `logger_output_verbose` is set to 1, providing additional details. ```log [2023-10-04T20:55:31.174304+00:00] report.ERROR: "Profile information": { "applicationClass": "Magento\ApplicationServer\App\Application\Interceptor", "applicationServer": "1", "threadPreviousRequestCount": "42", "memoryUsageBefore": "239568640 B", "memoryUsageAfter": "239686808 B", "memoryUsageAfterComparedToPrevious": "0 B", "memoryUsageDelta": "118168 B", "peakMemoryUsageBefore": "243053632 B", "peakMemoryUsageAfter": "243053632 B", "peakMemoryUsageDelta": "0 B", "wallTimeBefore": "2023-10-04T20:55:31.170300", "wallTimeAfter": "2023-10-04T20:55:31.174200", "wallTimeElapsed": "0.0038700103759766 s", "userTimeBefore": "3.771626 s", "userTimeAfter": "3.771626 s", "userTimeElapsed": "0 s", "systemTimeBefore": "0.095585 s", "systemTimeAfter": "0.099126 s", "systemTimeElapsed": "0.003541 s" } ``` -------------------------------- ### Example Log Output (Non-Verbose) Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/module-reference/module-application-performance-monitor.md This is an example of the performance metrics logged when `logger_output_verbose` is set to 0. ```log [2023-10-04T20:48:23.727037+00:00] report.ERROR: "Profile information": { "applicationClass": "Magento\ApplicationServer\App\Application\Interceptor", "applicationServer": "1", "threadPreviousRequestCount": "73", "memoryUsageAfter": "240 MB", "memoryUsageAfterComparedToPrevious": "0 B", "memoryUsageDelta": "118 KB", "peakMemoryUsageAfter": "243 MB", "peakMemoryUsageDelta": "0 B", "wallTimeElapsed": "0 s" } ``` -------------------------------- ### Example Theme Registration Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/build/component-registration.md This is an example of registering the 'luma' theme in the 'frontend' area. ```php use Magento\nFramework\nComponent\nComponentRegistrar; ComponentRegistrar::register(ComponentRegistrar::THEME, 'frontend/Magento/luma', __DIR__); ``` -------------------------------- ### POST Request Parameters Example Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/components/web-api/curl.md Example of how to structure the `$params` array for a POST request. ```php $params = [ 'user[email]' => $user->getEmail(), 'user[cellphone]' => $providerInfo['phone_number'], 'user[country_code]' => $providerInfo['country_code'], ] ``` -------------------------------- ### Example of Well-Named Commands with Vendor Prefix Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/cli-commands/naming-guidelines.md These examples show how to use a vendor prefix at the beginning of a command name to group related commands and improve clarity. ```terminal dev:myname:theme:create dev:myname:theme:delete ``` -------------------------------- ### Example Security.txt File Content Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/module-reference/module-securitytxt.md This is an example of a valid security.txt file, outlining contact information, encryption keys, acknowledgements, policy links, and signature location. ```txt Contact: mailto:security@example.com Contact: tel:+1-201-555-0123 Encryption: https://example.com/pgp.asc Acknowledgement: https://example.com/security/hall-of-fame Policy: https://example.com/security-policy.html Signature: https://example.com/.well-known/security.txt.sig ``` -------------------------------- ### After Method Plugin Example (Logging Login Activity) Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/components/plugins.md After methods can access the result (even if null) and arguments of the observed method. This example logs user login activity. ```php logger = $logger; } /** * @param Auth $authModel * @param null $result * @param string $username * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function afterLogin(Auth $authModel, $result, $username) { $this->logger->debug('User ' . $username . ' signed in.'); } } ``` -------------------------------- ### Example Field Declaration for Shortcut Icon Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/tutorials/admin/custom-admin-design.md This example demonstrates how to declare metadata for a 'head_shortcut_icon' field, including its database path, fieldset, backend model, and base URL configuration. ```xml design/head/shortcut_icon head Magento\Config\Model\Config\Backend\Image\Favicon media 1 favicon ``` -------------------------------- ### Run setup upgrade Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/build/component-management.md Execute this command after enabling or disabling a component to apply necessary database schema and data updates. ```bash bin/magento setup:upgrade ``` -------------------------------- ### Convert old scripts during setup:install Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/components/declarative-schema/migration-scripts.md Use this command to convert existing installation scripts to declarative schema when installing Adobe Commerce or Magento Open Source. The tool logs schema changes and persists them in db_schema.xml files. ```bash bin/magento setup:install --convert-old-scripts=1 ``` -------------------------------- ### Rollback Custom Customer Attribute Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/tutorials/admin/custom-dropdown-field-attribute.md This code removes a previously added custom customer attribute. It ensures proper rollback by starting and ending the database setup process. ```php // Start setup $this->moduleDataSetup->getConnection()->startSetup(); /** @var CustomerSetup $customerSetup */ $customerSetup = $this->customerSetupFactory->create(['setup' => $this->moduleDataSetup]); try { $customerSetup->removeAttribute( CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER, 'custom_options' ); } catch (Exception $e) { $this->logger->error($e->getMessage()); } // End setup $this->moduleDataSetup->getConnection()->endSetup(); ``` -------------------------------- ### Sample registration.php File Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/build/component-registration.md This is a sample registration.php file that registers a module. It demonstrates the basic structure required for component registration. ```php use Magento\nFramework\nComponent\nComponentRegistrar; ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Magento_AdminNotification', __DIR__); ``` -------------------------------- ### Deploy Sample Data from GitHub Repository Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/module-reference/module-sample-data.md Link your Magento instance with sample data cloned from the GitHub repository using a build script. ```bash php -f /dev/tools/build-sample-data.php -- --ce-source="" ``` -------------------------------- ### Check Module Version in UpgradeData Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/prepare/extension-lifecycle.md Use ModuleContextInterface to get the current module version and execute logic conditionally. This example checks if the version is less than '2.0.1' before proceeding with an upgrade. ```php startSetup(); if (version_compare($context->getVersion(), '2.0.1', '<')) { $this->upgradeHash($setup); } $setup->endSetup(); } ... } ``` -------------------------------- ### Securely Store Uploaded Files Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/security/file-uploads.md Use Magento's Filesystem class to get directory read/write interfaces for secure file storage. This example demonstrates reading from the VAR directory and writing to a custom module directory with a random file name. ```php class MyClass { private \Magento\Framework\Filesystem $filesystem; private \Magento\Framework\Filesystem\Directory\WriteFactory $writeFactory; private \Magento\Framework\Math\Random $rand; public function __construct( \Magento\Framework\Filesystem $filesystem, \Magento\Framework\Filesystem\Directory\WriteFactory $writeFactory, \Magento\Framework\Math\Random $rand ) { $this->filesystem = $filesystem; $this->writeFactory = $writeFactory; $this->rand = $rand; } ... public function workWithFiles(): void { ... //To read "MAGENTO_ROOT/var" sub-directories or files. $varDir = $this->filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR); //Going to write files into a designated folder specific to these type of files and functionality //Getting WriteInterface instance of `MAGENTO_ROOT/var/my-modules-dir` $thisModulesFilesDir = $this->writeFactory->create($varDir->getAbsolutePath('my-modules-dir')); //Random file name $randomFileName = $this->rand->getRandomString(32); //Copying a file from the system temporary directory into it's new path $thisModulesFilesDir->getDriver() ->copy($tmpUploadedOrGeneratedFilePath, $thisModulesFilesDir->getAbsolutePath($randomFileName)); } } ``` -------------------------------- ### Creating a Model Instance with a Factory Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/components/factories.md Demonstrates how to use the `create()` method on a factory to instantiate its corresponding model. This is the standard way to get a model instance. ```php $block = $this->blockFactory->create(); ``` -------------------------------- ### Avoid Unnecessary Logic: Get Customer and Store IDs Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/best-practices/extensions/security.md This example demonstrates a common scenario where customer and store IDs are retrieved but not immediately used in the subsequent logic. It's important to only fetch data when it's needed to optimize performance and avoid potential security risks associated with unused sensitive information. ```php public function getCustomerCart() { $customerId = (int) $this->getSession()->getCustomerId(); $storeId = (int) $this->getSession()->getStoreId(); if ($this->_cart !== null) { return $this->_cart; } ... $this->_cart = $this->quoteRepository->getForCustomer($customerId, [$storeId]); ... return $this->_cart; } ``` -------------------------------- ### Define Module Setup Version Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/tutorials/admin/create-admin-page.md If your module does not implement Declarative Schema, define the setup_version attribute in the module element of module.xml. ```xml ``` -------------------------------- ### Make a GET Request with cURL Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/components/web-api/curl.md Use the `get` method to perform a GET request and `getBody` to retrieve the response. ```php // get method $this->curl->get($url); // output of curl request $result = $this->curl->getBody(); ``` -------------------------------- ### Run GraphQL Application Server Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/components/app-server.md Execute this command to start the GraphQL Application Server from the CLI. ```bash bin/magento server:run ``` -------------------------------- ### Command Examples with Subject Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/cli-commands/naming-guidelines.md Demonstrates commands that include a subject to define a more specific set of actions within a group, like configuration or database schema/data operations. ```bash bin/magento setup:config:set bin/magento setup:config:delete bin/magento setup:db-schema:upgrade bin/magento setup:db-data:upgrade ``` -------------------------------- ### Check Version via HTTP GET Request Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/versioning/check-version.md Perform an HTTP GET request to `/magento_version` to get a less detailed application version string. ```text http:///magento_version ``` ```text Magento/2.3 (Community) ``` -------------------------------- ### Enable a component Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/build/component-management.md Use this command to enable a component and clear static content. Ensure you run setup:upgrade and cache:clean afterward. ```bash bin/magento module:enable --clear-static-content Component_Name ``` -------------------------------- ### InstallSchema.php for Schema Initialization Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/prepare/extension-lifecycle.md Implement this class to execute code during your module's initial schema installation. The application skips this stage if the schema version is already present in the setup_module table. ```php slowLoading = $slowLoading; } public function getFastValue() { return 'FastLoading value'; } public function getSlowValue() { return $this->slowLoading->getValue(); } } ``` -------------------------------- ### Example Language Package Registration Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/build/component-registration.md This is an example of registering the German language package for Magento. ```php use Magento\nFramework\nComponent\nComponentRegistrar; ComponentRegistrar::register(ComponentRegistrar::LANGUAGE, 'magento_de_de', __DIR__); ``` -------------------------------- ### Module File Structure Overview Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/build/component-file-structure.md Illustrates a typical file structure for a module, including common directories for block, controller, configuration, model, and setup classes. ```tree ├── Block ├── Controller ├── etc ├── Model │ ├── ResourceModel │ └── Collection ├── Setup └── ViewModel ``` -------------------------------- ### Test GET Endpoint Response Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/tutorials/backend/create-custom-rest-api.md This is a sample JSON response for a GET request to retrieve product details. ```json { "id": 1, "sku": "24-MB01", "name": "Joust Duffle Bag", "description": "

The sporty Joust Duffle Bag can't be beat - not in the gym, not on the luggage carousel, not anywhere. Big enough to haul a basketball or soccer ball and some sneakers with plenty of room to spare, it's ideal for athletes with places to go.

\n

    \n
  • Dual top handles.
  • \n
  • Adjustable shoulder strap.
  • \n
  • Full-length zipper.
  • \n
  • L 29\" x W 13\" x H 11".
  • \n
" } ``` -------------------------------- ### Minimal module.xml for component declaration Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/build/component-name.md Declare your component's name and existence in the `module.xml` file. The `name` parameter is mandatory. Include `setup_version` if not using Declarative Schema. ```xml ``` -------------------------------- ### Configure Performance Monitor Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/module-reference/module-application-performance-monitor.md Add these lines to `app/etc/env.php` to enable and configure the performance monitor. Use 0 or 1 to enable or disable. ```php 'application' => [ 'performance_monitor' => [ 'logger_output_enable' => 1, 'logger_output_verbose' => 0, ] ] ``` -------------------------------- ### Example of a Poorly Named Command Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/cli-commands/naming-guidelines.md This example demonstrates a command name that is not obvious and difficult to remember due to its structure. ```terminal myname:dev:theme:create ``` -------------------------------- ### Instantiate Object with Default Dependencies Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/development/components/object-manager/helper.md Use this to create an object with all its dependencies automatically mocked by the helper class. ```php $objectManagerHelper = new \Magento\TestFramework\Helper\ObjectManager($this); // default constructor arguments $scopePool = $objectManagerHelper->getObject('\Magento\App\Config\ScopePool'); ``` -------------------------------- ### Example Method DocBlock Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/coding-standards/docblock.md Illustrates the correct structure and content for a method DocBlock, including descriptions, parameter, return, and exception annotations. ```php /** * Merge the config XML files * * @param array $configFiles * @return void * @throws \Magento\Exception if a non-existing or invalid XML file passed */ protected function merge($configFiles) { $domConfig = new \Magento\Config\Dom($this->_getInitialXml(), $this->_getIdAttributes()); foreach ($configFiles as $file) { if (!file_exists($file)) { throw new \Magento\Exception("File does not exist: {$file}"); } $domConfig->merge(file_get_contents($file)); if (!$domConfig->validate($this->getSchemaFile(), $errors)) { $message = "Invalid XML file: {$file}\n"; /** @var libXMLError $error */ foreach ($errors as $error) { $message .= "{$error->message} Line: {$error->line}\n"; } throw new \Magento\Exception($message); } } $this->_dom = $domConfig->getDom(); } ``` -------------------------------- ### Install OpenSwoole PHP Extension Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/module-reference/module-application-server.md Install the OpenSwoole PHP extension and its corresponding Composer package. Ensure you use compatible versions. ```bash pecl install openswoole-22.0.0 | composer require openswoole/core:22.1.1 ``` -------------------------------- ### Deploy Sample Data using Magento CLI Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/module-reference/module-sample-data.md Use this command to deploy sample data packages from the Magento composer repository via the Magento command-line interface. ```bash composer install ``` ```bash bin/magento sampledata:deploy ``` -------------------------------- ### Test GET Endpoint Request Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/tutorials/backend/create-custom-rest-api.md Use this format to test a GET endpoint. Replace placeholders with your domain, store code, and product ID. ```http GET /rest/V1//rest_dev/getProduct/ ``` -------------------------------- ### DocBlock for Implementation Source: https://github.com/adobedocs/commerce-php/blob/main/src/pages/coding-standards/docblock.md Example of a DocBlock for a class implementation, mirroring interface documentation. ```php