Console

Table of contents

  1. Overview
  2. When to Use the Console
  3. Summary of Available Commands
  4. Building Your Own Command
  5. Command Helpers
  6. Tools


1. Overview Table of Contents

The Chappy.php framework includes a built-in command-line interface (CLI) for managing routine development tasks such as generating files, running tests, seeding the database, and launching local servers. Check out Symfony’s Console component page for additional documentation.

You can run a console command following the following syntax:

php console ${command_name} ${argument}

An example of a command that requires arguments is demonstrated below:

php console test Test

Where Test is the name of the file containing the test. Typing php console in the command line at project root will display all of the available commands. Each of the supported commands will be covered in their respective sections in this user guide.

If there is a command you would like for us to support you can submit an issue here.


2. When to Use the Console Table of Contents

The console is ideal for:

  • Generating boilerplate (models, controllers, views, etc.)
  • Running migrations and seeders
  • Executing unit tests
  • Serving the app locally (via PHP)
  • Creating custom tools for automation


3. Summary of Available Commands Table of Contents

You can list all available commands at any time by running:

php console


A. Generators

Command Description Arguments
make:acl Generates a new menu_acl json file  
make:command Generates a new command class  
make:command:helper Generates helper class that supports console commands  
make:component Generates component based on flags that are set --card,
--form,
--table
make:controller Generates a new controller class --layout,
--resource
make:css Generates a new CSS file  
make:email Generates a file for an E-mail  
make:email:layout Generates an E-mail template  
make:event Generates a new Event class --queue
make:factory Creates a new factory class  
make:job Generates a new job class  
make:layout Generates a new layout --menu,
--menu-acl
make:listener Generates new listener class --event,
--queue
make:mailer Generates a new custom mailer class  
make:menu Generates a new menu file  
make:migration Generates a Database Migration --update,
--rename
make:model Generates a new model file --upload
make:notification Generates a new notification class --channels
make:provider Generates a new event service provider class  
make:seeder Creates a new database seeder class --factory
make:service Generates a new service class  
make:test Generates a new test class --feature
make:test:builder Generates a new test builder class  
make:test:runner Generates a new test runner class  
make:validator Generates a new custom form validator class  
make:view Create a new view  
make:widget Creates a new widget  


B. Migrations & Seeders

Command Description Arguments
migrate Runs a Database Migration --seed,
--seeder
migrate:drop:all Drops all database tables  
migrate:fresh Drops all tables and performs migration --seed,
--seeder
migrate:restore Restores built-in migrations  
migrate:refresh Drops all tables with down function and runs a Database Migration --seed,
--step,
--seeder
migrate:rollback Performs rollback operation --step,
--batch
migrate:status Reports status of migrations  
seed:run Runs database seeders --seeder


C. Local Servers

Command Description Arguments
serve Runs local PHP standalone server --host, --port
serve:api Locally serves API using built in PHP server --host, --port
serve:docs Locally serves jekyll based user guide --host, --port

Each of these commands can accept the following flags:

  • --host - Hostname or ipaddress
  • --port - Overrides default port


D. Notifications

Command Description Arguments
notifications:migration Creates new migration for the notifications table  
notifications:prune Prunes table base on value older than days set --days
notifications:test Tests a notification through specified channels --user,
--channels,
--dry-run,
--with


E. Queue

Command Description Arguments
queue:migration Creates new migration for queue table  
queue:worker Starts a new queue worker --once,
--max,
--queue


F. Testing

Command Description Arguments
test Performs a phpunit test --feature,
--unit,
--coverage,
--debug,
--display-depreciations,
--display-errors,
--display-incomplete,
--display-skipped,
--fail-on-complete,
--fail-on-risky,
--testdox,
--random-order,
--reverse-order,
--stop-on-error,
--stop-on-failure,
--stop-on-incomplete,
--stop-on-risky,
--stop-on-skipped,
--stop-on-warning
tinker Launches tinker shell  


G. Tools

Command Description Arguments
log:clear Deletes existing log file --all,
--app,
--cli,
--unit
tools:rm-profile-images Removes all profile images  


H. React

Command Description Arguments
react:auth Generates page components for the auth controller  
react:component Generates a react component --named
react:error Restores error/NotFound.jsx page component  
react:home Generates Index.jsx page component for the home controller  
react:hook Generates a new React.js hook file  
react:page Generates a new react component for views  
react:profile Generates page components for the profile controller  
react:util Generates a JavaScript utility file to support React.js  


I. Vitest

Command Description Arguments
react:make:test Generates a new test case file --component,
--unit,
--view
react:test Performs Vitest unit tests --component,
--unit,
--view


4. Building Your Own Command Table of Contents

Generating your own command is easy. We will make a fake command called Foo as an example. Simply run the following in your terminal under project root:

php console make:command Foo

The output of this command will be a file called FooCommand.php and will be located under app/Lib/Console/Commands. The console application will throw an error until you set the name of the command. The resulting file is shown below:

namespace App\Lib\Console\Commands;
 
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

/**
 * Undocumented class
 */
class FooCommand extends Command {
    /**
     * Configures the command.
     *
     * @return void
     */
    protected function configure(): void
    {
        //
    }

    /**
     * Executes the command
     *
     * @param InputInterface $input The input.
     * @param OutputInterface $output The output.
     * @return int A value that indicates success, invalid, or failure.
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        //
    }
}

Everything you need to build your own command is included in this file. All relevant imports are listed at the top. Each command you create contains two functions. The configure function is where everything gets setup and the execute function performs actions associated with the command.


5. Command Helpers Table of Contents

Since this framework is fully Object-Oriented you can generate helper files to modularize tasks that need to be used across multiple commands. Helpers can be found at app\Lib\Console\Helpers.

You can build your own command helper class by running the make:command-helper command. Let’s create a FooHelper class by running the following:

php console make:command:helper FooHelper

Once your run this command the file generated will look as follows:

namespace App\Lib\Console\Helpers;

use Symfony\Component\Console\Command\Command;

/**
 * 
 */
class FooHelper {

}

When adding function we usually create those that are static. We rarely need to create a new instance of a helper class so a constructor is not included in the output.


6. Tools Table of Contents

Tools is a command helper class that contains functions that are commonly used with other commands. To use the tools class simply used the following use statement:

use Console\Helpers\Tools;


A. border Function

The border prints a dashed line.


B. createDirWithPrompt

Creates a directory. It checks if it already exists. If not, user is asked to confirm the want to create a new directory.

Parameters

  • string $directory - The full path for the directory to be created.
  • InputInterface $cmdInput - The Symfony InputInterface object.
  • OutputInterface $cmdOutput - The Symfony OutputInterface object.

Returns

  • array - An array containing the contents of the $inputName variable.
  • int - A value that indicates success, invalid, or failure.

Example

$directory = View::VIEW_PATH.$viewArray[0];
$isDirMade = Tools::createDirWithPrompt($directory, $input, $output);
if($isDirMade == Command::FAILURE) return Command::FAILURE;

In the above example we use the result of this function’s call to test if there is a failure. In this case we return Command::FAILURE.


C. dotNotificationVerify

Checks if input is in dot notation. If in dot notation the string is placed in an array where the first index is the directory name. The second element is the file name. The structure is shown below:

["directory_name","file_name"]

If not in the <directory_name>.<file_name> an error message is displayed an a Command::FAILURE integer value is returned.

Parameters

  • string $inputName - The name in <directory_name>.<file_name> format.

Returns

  • array - An array containing the contents of the $inputName variable.
  • int - If $inputName is not in correct format then Command::FAILURE is returned.

Example

$viewArray = Tools::dotNotationVerify('view-name', $input);
if($viewArray == Command::FAILURE) return Command::FAILURE;

In the above example we use the result of the dotNotification Verify function call to test if there are any failures. In this case we return Command::FAILURE.


D. info Function

The info function is used to present to the user logging information. The following is an example of how to call this function:

ConsoleLogger::log("My message", Logger::INFO, Tools::BG_RED, Tools::TEXT_WHITE);

This function can be called using the console() global using the same parameters.

The frequency of the output for various severity levels depends on the value of the LOGGING environmental variable in the .env file. If the level is set to notice then logging set to a lower level are ignored.

Parameters

  • string $message - The message we want to show.
  • string $level - The level of severity for log file. The valid levels are info, debug, warning, error, critical, alert, and emergency.
  • string $background - The background color. This function supports black, red, green, yellow, blue, magenta, cyan, and `light-grey.
  • string $text - The color of the text. This function supports black, white, dark-grey, red, green, brown, blue, magenta, cyan, light-cyan, light-grey, light-red, light green, light-blue, and light-magenta.

We usually don’t use the fourth argument since it may sometimes be ignored especially if you are using the terminal that comes with Visual Studio Code.


Globals

Global functions for console logging are also available based on severity level.

  • console_emergency($message) - Prints emergency message with red background.
  • console_alert($message) - Prints alert message with red background.
  • console_critical($message) - Prints critical message with magenta background.
  • console_error($message) - Prints error message with red background.
  • console_warning($message) - Prints warning message with yellow background.
  • console_notice($message) - Prints notice message with cyan background.
  • console_info($message) - Prints info message with green background.
  • console_debug($message) - Prints debug message with blue background.


The standard Logger Alert Levels (Based on PSR-3)

Severity Level Description
Logger::EMERGENCY System is unusable (e.g., database crash, critical application failure).
Logger::ALERT Immediate action required (e.g., entire system down, security breach).
Logger::CRITICAL Critical errors (e.g., service failures, unexpected shutdowns).
Logger::ERROR Application errors (e.g., exceptions, failed transactions, runtime errors).
Logger::WARNING Warning messages (e.g., deprecated features, high memory usage).
Logger::NOTICE Normal but significant events (e.g., config changes, recoverable issues).
Logger::INFO Informational messages (e.g., user logins, API requests, background jobs).
Logger::DEBUG Debugging details (e.g., variables, performance metrics).

A LoggerLevelException is thrown if the $level parameter does not match a supported Logger Alert Level.

The following is a list of supported background colors (const):

  1. Tools::BG_BLACK
  2. Tools::BG_RED
  3. Tools::BG_GREEN
  4. Tools::BG_YELLOW
  5. Tools::BG_BLUE
  6. Tools::BG_MAGENTA
  7. Tools::BG_CYAN
  8. Tools::BG_LIGHT_GREY

The following text colors are supported (const):

  1. Tools::TEXT_BLACK
  2. Tools::TEXT_WHITE
  3. Tools::TEXT_DARK_GREY
  4. Tools::TEXT_RED
  5. Tools::TEXT_GREEN
  6. Tools::TEXT_BROWN
  7. Tools::TEXT_YELLOW
  8. Tools::TEXT_BLUE
  9. Tools::TEXT_MAGENTA
  10. Tools::TEXT_CYAN
  11. Tools::TEXT_LIGHT_CYAN
  12. Tools::TEXT_LIGHT_GREY
  13. Tools::TEXT_LIGHT_RED
  14. Tools::TEXT_LIGHT_GREEN
  15. Tools::TEXT_LIGHT_BLUE
  16. Tools::TEXT_LIGHT_MAGENTA

A ConsoleException is thrown if you use a value for text color in place of background color and vice versa. If a value provided for $background and $text does not match any of the supported colors this exception is also thrown.


E. writeFile Function

The writeFile function is what we used when we need to dump contents of a command to a file. We use this for commands such as making controllers, models, and migrations.

Here is an example call to this function for generating a new menu_acl json file.

public static function makeMenuAcl(InputInterface $input): int {
    $menuName = $input->getArgument('acl-name');
    return Tools::writeFile(
        ROOT.DS.'app'.DS.strtolower($menuName)."_menu_acl.json",
        self::menuAcl($menuName),
        "Menu file"
    );
}

Since we need to name this file we grab the argument provided when running the command in the console. The writeFile function contains the following arguments:

  1. $path - Where the file will be written
  2. $content - The contents of the file to be created
  3. $name The name of the file, class, or other relevant information.

Use DS instead of / or \ for cross-platform compatibility.

We return an integer to indicate success, invalid, or failure.

The path will usually contain the name variable, in this case, the name of the menu. We always use the DIRECTORY_SEPARATOR (DS) constant instead of forward or backward slashes to ensure compatibility across different operating systems.

The self::menuAcl($menuName) calls a function that generates the content. We prefer to use a separate function for the content to make the code clean and more maintainable.

The third argument is used to populate the message that gets printed out to the terminal. In the case the messages will be Menu file successfully created when file write is successful and Menu file already exists if the file already exists.