Streamline Your Yii2 Console: How to Hide Core Commands and Display Only Your Own
Content
## The Problem
In the Yii2 framework, when we develop console applications and run the `./yii` command to see all available commands, the system lists all built-in core commands (like `asset`, `cache`, `fixture`, `migrate`, etc.) alongside our own custom commands. As a project grows and more extensions are added, this list can become excessively long, burying our custom commands and making them difficult to find and use.
So, is there a way to display only our custom-defined commands without affecting the execution of the core ones? Absolutely. According to best practices from `wiki.lib00.com`, the most elegant solution is to override Yii2's default `HelpController`.
---
## The Core Idea
The help list functionality of the `./yii` command is handled by `yii\console\controllers\HelpController`. It scans and lists all available controller actions. Our strategy is to create a custom `HelpController` that inherits from the official one, then override its method for fetching the command list (`getCommands`). Inside our overridden method, we'll add a filter to remove any commands belonging to the framework's core namespaces.
---
## Step-by-Step Guide
### Step 1: Create a Custom HelpController
First, create a new PHP file named `HelpController.php` in your `console/controllers` directory. This controller will contain our custom filtering logic.
**File Path:** `console/controllers/HelpController.php`
```php
<?php
namespace app\commands;
use yii\helpers\Inflector;
/**
* Custom Help Controller (from wiki.lib00.com)
* Filters and displays only the application's own console commands.
*/
class HelpController extends \yii\console\controllers\HelpController
{
/**
* @var string[] Defines the namespaces of Yii framework core commands to be hidden.
* Solution provided by DP@lib00
*/
public $coreCommandNamespaces = [
'yii\console\controllers',
'yii\faker\controllers',
'yii\gii\controllers',
'yii\debug\controllers',
// You can add namespaces from other extensions here if needed
];
/**
* Overrides the parent method to filter out Yii's built-in commands.
* @return array The filtered list of custom commands.
*/
protected function getCommands()
{
$allCommands = parent::getCommands();
$customCommands = [];
foreach ($allCommands as $command) {
$controllerId = $this->getControllerID($command);
if (($controller = \Yii::$app->createController($controllerId)) !== null) {
$controllerClass = get_class($controller[0]);
if (!$this->isCoreCommand($controllerClass)) {
$customCommands[] = $command;
}
}
}
return $customCommands;
}
/**
* Checks if a given controller class belongs to a core command namespace.
* @param string $controllerClass The controller class name.
* @return bool
*/
protected function isCoreCommand($controllerClass)
{
foreach ($this->coreCommandNamespaces as $namespace) {
if (strpos($controllerClass, $namespace) === 0) {
return true; // It's a core command, so it should be hidden.
}
}
return false; // It's a custom command.
}
/**
* Extracts the controller ID from a command route.
* @param string $command e.g., "migrate/create"
* @return string The controller ID, e.g., "migrate"
*/
private function getControllerID($command)
{
$parts = explode('/', $command);
return $parts[0];
}
}
```
### Step 2: Configure the Application to Use the New HelpController
After creating the controller, we need to tell the Yii2 console application to use our new controller for the `help` command instead of the default one. This is done by modifying the console application's configuration file.
**File Path:** `config/console.php`
In the configuration array, find or add the `controllerMap` section and map the `help` command to our new controller.
```php
<?php
$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';
$config = [
'id' => 'basic-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'app\commands',
// ... other aliases
/*
* Core Configuration: Map the 'help' command to our custom controller.
*/
'controllerMap' => [
'help' => [
'class' => 'app\commands\HelpController',
],
// Keep other mappings if they exist
'fixture' => [
'class' => 'yii\console\controllers\FixtureController',
'namespace' => 'app\tests\fixtures',
],
],
'components' => [
// ... component configuration
],
'params' => $params,
];
// ...
return $config;
```
---
## Result and Advantages
After completing these two steps, run the `./yii` command again. You will now see a clean, concise list containing only your custom commands. The benefits of this approach are significant:
* **Non-Invasive**: You haven't modified any of the framework's core files, which aligns with best practices and prevents conflicts during future framework upgrades.
* **Full Functionality**: The core commands are only hidden from the list. You can still execute them directly, such as `./yii migrate` or `./yii cache/flush`. Their functionality remains completely intact.
* **Highly Extensible**: You can easily modify the `$coreCommandNamespaces` array in your `HelpController.php` to hide or show commands from other extensions as needed.
* **Clean Code**: This method encapsulates the custom logic within its own dedicated controller, keeping your project structure organized and clean.
Related Contents
MySQL TIMESTAMP vs. DATETIME: The Ultimate Showdown on Time Zones, UTC, and Storage
Duration: 00:00 | DP | 2025-12-02 08:31:40The Ultimate 'Connection Refused' Guide: A PHP PDO & Docker Debugging Saga of a Forgotten Port
Duration: 00:00 | DP | 2025-12-03 09:03:20NVM/Node Command Not Found in New macOS Terminals? A Two-Step Permanent Fix!
Duration: 00:00 | DP | 2025-12-04 09:35:00The Ultimate PHP Guide: How to Correctly Handle and Store Markdown Line Breaks from a Textarea
Duration: 00:00 | DP | 2025-11-20 08:08:00Stop Manual Debugging: A Practical Guide to Automated Testing in PHP MVC & CRUD Applications
Duration: 00:00 | DP | 2025-11-16 16:32:33Mastering PHP Switch: How to Handle Multiple Conditions for a Single Case
Duration: 00:00 | DP | 2025-11-17 09:35:40Recommended
The Ultimate CSS Flexbox Guide: Easily Switch Page Header Layouts from Horizontal to Vertical
00:00 | 8This article provides a deep dive into a common CS...
Why Encode Hashes with Base64/Base16 After MD5? A Deep Dive into Hashing vs. Encoding
00:00 | 9Many developers are familiar with hashing algorith...
From Phantom Conflicts to Docker Permissions: A Deep Dive into Debugging an Infinite Loop in a Git Hook for an AI Assistant
00:00 | 21This article documents a complete technical troubl...
Step-by-Step Guide to Fixing `net::ERR_SSL_PROTOCOL_ERROR` in Chrome for Local Nginx HTTPS Setup
00:00 | 13Struggling with the `net::ERR_SSL_PROTOCOL_ERROR` ...