Skip to content

Latest commit

 

History

History
187 lines (133 loc) · 2.5 KB

File metadata and controls

187 lines (133 loc) · 2.5 KB

PHP can be used to create command-line scripts (CLI) much like shell scripts.

Basic CLI Script

#!/usr/bin/env php
<?php

echo "Hello World\n";

Make executable:

chmod +x hello.php
./hello.php

Or run directly:

php hello.php

Reading Command Arguments

<?php

$name = $argv[1] ?? 'Guest';

echo "Hello {$name}\n";

Run:

php greet.php John

Output:

Hello John

Database Script Example

<?php

require __DIR__ . '/bootstrap.php';

$userRepository = new UserRepository(
    Database::getConnection()
);

$users = $userRepository->findAll();

foreach ($users as $user) {
    echo "{$user->id} {$user->email}\n";
}

Run:

php scripts/list-users.php

Command Pattern

For multiple commands:

interface Command
{
    public function execute(array $args): int;
}
class CreateUserCommand implements Command
{
    public function execute(array $args): int
    {
        echo "Creating user...\n";

        return 0;
    }
}

Dispatcher:

$commands = [
    'create-user' => new CreateUserCommand(),
];

$commandName = $argv[1] ?? '';

if (!isset($commands[$commandName])) {
    exit("Unknown command\n");
}

exit(
    $commands[$commandName]->execute(
        array_slice($argv, 2)
    )
);

Usage:

php app.php create-user

Using Symfony Console (Recommended)

For professional CLI applications, use Symfony Console.

Install:

composer require symfony/console

Example:

class ListUsersCommand extends Command
{
    protected static $defaultName = 'users:list';

    protected function execute(
        InputInterface $input,
        OutputInterface $output
    ): int {
        $output->writeln('Listing users');

        return Command::SUCCESS;
    }
}

Run:

php bin/console users:list

Benefits:

  • Options (--email=test@example.com)
  • Arguments validation
  • Tables and formatted output
  • Progress bars
  • Interactive prompts
  • Auto-generated help

Typical structure:

project/
├── bin/
│   └── console
├── src/
│   ├── Command/
│   │   ├── ListUsersCommand.php
│   │   └── CreateUserCommand.php
│   ├── Repository/
│   ├── Entity/
│   └── Service/
└── composer.json

For anything beyond a couple of scripts, Symfony Console is the standard approach in modern PHP applications.