Oihana PHP Commands

LifecycleTrait uses trait:short

Provides helper methods to manage the lifecycle of console commands.

This trait defines utility methods for initializing and finalizing Symfony Console commands with consistent output formatting. It is intended to be used alongside IOTrait to handle SymfonyStyle input/output operations.

Responsibilities

  • Displaying a formatted title when a command starts.
  • Returning a start timestamp for execution time calculation.
  • Displaying a completion message with optional execution time.

Usage Example

use oihana\commands\traits\LifecycleTrait;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class MyCommand extends Command
{
    use LifecycleTrait;

    protected static $defaultName = 'app:my-command';

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        // Start the command
        [$io, $startTime] = $this->startCommand($input, $output);

        // ... perform command actions ...

        // End the command
        return $this->endCommand($input, $output, ExitCode::SUCCESS, $startTime);
    }
}
Tags
author

Marc Alcaraz

since
1.0.0

Table of Contents

Properties

$io  : SymfonyStyle|null
The command writer.

Methods

batchIOActions()  : void
Executes a batch of IO-aware callback actions using `runIOAction()`.
endCommand()  : int
Finalizes the command execution.
getIO()  : SymfonyStyle
Returns the IO writer reference.
runAction()  : mixed
Executes a callback within a styled Symfony Console context (IO).
runIOAction()  : mixed
Executes a callback within a styled Symfony Console context (IO).
startCommand()  : SymfonyStyle, 1: float}
Initializes the command execution.

Properties

$io

The command writer.

public SymfonyStyle|null $io = null

Methods

batchIOActions()

Executes a batch of IO-aware callback actions using `runIOAction()`.

public batchIOActions([array<string|int, mixed> $actions = [] ][, SymfonyStyle|null $io = null ][, bool $numbering = false ]) : void

This method takes an array of associative arrays (actions), each containing:

  • callback (callable, required): the function to execute.
  • title (string, optional): a section title to print before the callback.
  • finish (string, optional): a message to print after the callback completes.
  • endLines (int, optional): number of newlines to append at the end (default: 2).

The provided $io instance is passed to all actions for styled output. If no callback is provided in an action, that entry is skipped.

Parameters
$actions : array<string|int, mixed> = []

An array of actions to run, each as an associative array with keys:

  • callback (callable): required
  • title (string): optional
  • finish (string): optional
  • endLines (int): optional, defaults to 2
$io : SymfonyStyle|null = null

Optional SymfonyStyle instance for styled output.

$numbering : bool = false
Tags
example
$this->batchIOActions
([
    [
        'callback'  => fn(SymfonyStyle $io) => $this->initializeDb($io),
        'title'     => 'Step 1: Database Initialization',
        'finish'    => '✅ Done.',
        'endLines'  => 1,
    ],
    [
        'callback'  => fn(SymfonyStyle $io) => $this->migrateData($io),
        'title'     => 'Step 2: Data Migration',
    ],
]);

endCommand()

Finalizes the command execution.

public endCommand(InputInterface $input, OutputInterface $output[, int $status = ExitCode::SUCCESS ][, float $timestamp = 0 ]) : int

Displays a completion section in the console output with an optional execution time, followed by a short farewell message. Returns the provided status code.

Parameters
$input : InputInterface

The console input instance.

$output : OutputInterface

The console output instance.

$status : int = ExitCode::SUCCESS

The return status code (default: ExitCode::SUCCESS).

$timestamp : float = 0

The starting UNIX timestamp for execution time calculation (default: 0).

Tags
example
return $this->endCommand($input, $output, ExitCode::SUCCESS, $startTime);
Return values
int

The status code to return from the command.

getIO()

Returns the IO writer reference.

public getIO(InputInterface $input, OutputInterface $output) : SymfonyStyle
Parameters
$input : InputInterface
$output : OutputInterface
Return values
SymfonyStyle

runAction()

Executes a callback within a styled Symfony Console context (IO).

public runAction(callable $callback[, InputInterface|null $input = null ][, OutputInterface|null $output = null ][, string $title = '' ][, string $finish = '' ][, int $endLines = 1 ][, callable|null $getIO = null ]) : mixed

This method ensures consistent output formatting by wrapping the given callback in a SymfonyStyle context. If both $input and $output are provided, it automatically creates or retrieves a SymfonyStyle instance using either the internal getIO() method or a custom $getIO callable. It optionally renders a section title before execution, a closing message after execution, and appends a number of newlines at the end.

If $input or $output are null, the method simply invokes the callback without styling.

Parameters
$callback : callable

The main logic to execute. If IO is available, the callable should accept a SymfonyStyle argument.

$input : InputInterface|null = null

Optional Symfony Console input interface.

$output : OutputInterface|null = null

Optional Symfony Console output interface.

$title : string = ''

Optional title printed as a section header before executing the callback.

$finish : string = ''

Optional closing message printed after executing the callback.

$endLines : int = 1

Number of new lines to append after the action (default: 2).

$getIO : callable|null = null

Optional callable to retrieve a custom SymfonyStyle instance (receives $input, $output).

Tags
example
$this->runAction
(
    callback : fn( ?SymfonyStyle $io ) => $this->wordPressInitializeDatabase( verbose:$verbose ) ,
    input    : $input ,
    output   : $output ,
    title    : '01. Initialize the Mysql Database' ,
    finish   : '🗄️ The WordPress database is ready.'
);
Return values
mixed

The return value from the callback.

runIOAction()

Executes a callback within a styled Symfony Console context (IO).

public runIOAction(callable $callback[, SymfonyStyle|null $io = null ][, string $title = '' ][, string $finish = '' ][, int $endLines = 2 ]) : mixed

This method runs the given callback, passing the provided SymfonyStyle instance to it for consistent console output formatting. It optionally displays a section title before executing the callback and a finishing message afterward. Finally, it appends a specified number of new lines.

If no title is given, no section header is printed. If no finish message is given, no closing message is printed.

Parameters
$callback : callable

The callable to execute. Receives the SymfonyStyle instance as an argument.

$io : SymfonyStyle|null = null

The SymfonyStyle instance used for console output.

$title : string = ''

Optional section title displayed before running the callback.

$finish : string = ''

Optional finishing message displayed after the callback completes.

$endLines : int = 2

Number of new lines to append after the finishing message (default is 2).

Tags
example
$this->runIOAction(
    callback: fn( ?SymfonyStyle $io) => $this->wordPressInitializeDatabase(verbose: $verbose),
    io: $io,
    title: '01. Initialize the Mysql Database',
    finish: '🗄️ The WordPress database is ready.'
);
Return values
mixed

The return value from the callback.

startCommand()

Initializes the command execution.

protected startCommand(InputInterface $input, OutputInterface $output) : SymfonyStyle, 1: float}

Displays a formatted title in the console containing the command name and an optional action property, then returns the I/O helper instance and the current UNIX timestamp.

Parameters
$input : InputInterface

The console input instance.

$output : OutputInterface

The console output instance.

Tags
example
[$io, $startTime] = $this->startCommand($input, $output);
Return values
SymfonyStyle, 1: float}

An array containing the SymfonyStyle I/O instance and the current timestamp.


        
On this page

Search results