Console Commands
Table of contents
Loading...Introduction
To execute a function of a PHP class that is instantiated by the container
via console commands, a library such as symfony/console
can be help.
But simple use-cases can be covered by a little PHP script that bootstraps the application, retrieves the container and the required class instance from it and calls the requested function.
Script setup
File: bin/console.php
<?php
// Boot the application
$app = require __DIR__ . '/../config/bootstrap.php';
/** Get the container instance @var Psr\Container\ContainerInterface $container */
$container = $app->getContainer();
// The $argv variable is an array that contains the command-line arguments passed to the script.
// The first element of the $argv array is always the name of the script itself ('bin/console.php').
// array_shift($argv) removes this first element that is not relevant here.
array_shift($argv);
// The now first parameter after the script name that was removed is the class name.
// The second element in the $argv array is the function name.
[$containerKey, $functionName] = $argv;
// Retrieve the instance corresponding to the $containerKey form the container.
$objectInstance = $container->get($containerKey);
// The call_user_func_array function is used to call the specified function on the retrieved instance.
// In this case, it's calling the function specified by $functionName on the object instance.
// The second parameter is an empty array, which means no parameters are passed to the function.
call_user_func_array([$objectInstance, $functionName], []);
Usage
Container definition
The class to be used for the command line should be defined with a string key and not the fully qualified class name to shorten the command line call.
For example, the SqlSchemaGenerator
class from the
samuelgfeller/test-traits
library
can be defined with the container key
'SqlSchemaGenerator'
and instantiated as shown below.
More information on this use-case:
Generating the schema file.
File: config/container.php
return [
// ...
'SqlSchemaGenerator' => function (ContainerInterface $container) {
return new \TestTraits\Console\SqlSchemaGenerator(
$container->get(PDO::class),
// Schema output folder
$container->get('settings')['root_dir'] . '/resources/schema'
);
},
];
Command line call
The bin/console.php
script can be used to call the generateMySqlSchema()
function
from the SqlSchemaGenerator
class.
The first parameter is the container key which returns the class instance containing
the function of the second parameter:
php bin/console.php SqlSchemaGenerator generateMySqlSchema
Composer script integration
For added convenience, this command can be integrated into the composer scripts and be executed under an alias.
File: composer.json
"scripts": {
"schema:generate": "php bin/console.php SqlSchemaGenerator generateMySqlSchema"
}
The command can then be executed like this:
composer schema:generate