Catalog / Magento 2 Cheatsheet

Magento 2 Cheatsheet

A quick reference guide for Magento 2 developers, covering essential commands, configurations, code snippets, and best practices.

Essential CLI Commands

Setup Commands

setup:upgrade

Upgrades Magento modules and database schema.

setup:di:compile

Compiles dependency injection configurations.

setup:static-content:deploy

Deploys static view files.

setup:cache:clean

Cleans Magento cache.

setup:cache:flush

Flushes Magento cache storage.

setup:config:set

Sets configuration values.

Cache Management

cache:enable [types]

Enables specified cache types.

cache:disable [types]

Disables specified cache types.

cache:status

Shows the status of Magento cache types.

Index Management

indexer:reindex [index]

Reindexes specified indexers.

indexer:info [index]

Shows information about indexers.

indexer:reset [index]

Resets indexers.

indexer:status [index]

Shows the status of indexers.

File System

Directory Structure

app/code - Custom modules.

app/design - Custom themes.

vendor - Composer dependencies.

pub/static - Static files (CSS, JS, images).

var - Cache, logs, sessions.

generated - Generated classes (proxies, factories).

File Permissions

Set file permissions to 777 for the var, pub/static, generated directories during development.

chmod -R 777 var pub/static generated

For production environments, follow Magento’s official security guidelines for file permissions.

Code Snippets

Object Manager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Catalog\Model\Product')->load(1);

Note: Avoid using Object Manager directly in your code. Use dependency injection instead.

Dependency Injection

/**
 * @param \Magento\Catalog\Model\Product $product
 */
public function __construct(
    \Magento\Catalog\Model\Product $product
) {
    $this->product = $product;
}

Events

Example of dispatching an event:

$this->_eventManager->dispatch(
    'custom_event',
    ['data' => $data]
);

Example of listening to an event, in events.xml:

<event name="custom_event" observer="Custom\Module\Observer\CustomObserver" />

Database Operations

Resource Model

$resource = $this->getResource();
$connection = $resource->getConnection();

$select = $connection->select()
    ->from($resource->getTableName('your_table'))
    ->where('field = ?', $value);

$result = $connection->fetchRow($select);

InstallSchema

Example of creating a table in InstallSchema.php:

$table = $setup->getConnection()->newTable(
    $setup->getTable('your_table')
)->addColumn(
    'id',
    \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
    null,
    ['identity' => true, 'nullable' => false, 'primary' => true],
    'ID'
);
$setup->getConnection()->createTable($table);