First i install symfony/console composer require symfony/console
In my app folder i create the an “cli.php” file:
<?php
use DI\ContainerBuilder;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\InputOption;
return function (ContainerBuilder $containerBuilder) {
$containerBuilder->addDefinitions([
Application::class => function (ContainerInterface $c) {
$application = new Application();
$application->getDefinition()->addOption(
new InputOption('--env', '-e', InputOption::VALUE_REQUIRED, 'The Environment name.', 'development')
);
foreach ($c->get('settings')['commands'] as $class) {
$application->add($c->get($class));
}
return $application;
},
]);
};
In my index.php (located in public folder):
// Set up command line
$cli = require __DIR__ . '/../app/cli.php';
$cli($containerBuilder);
I created an example command in src/Command/ExampleCommand.php:
<?php
namespace App\Console;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Command.
*/
final class ExampleCommand extends Command
{
/**
* @var ContainerInterface
*/
private $container;
/**
* Constructor.
*
* @param ContainerInterface $container The container
* @param string|null $name The name
*/
public function __construct(ContainerInterface $container, ?string $name = null)
{
parent::__construct($name);
$this->container = $container;
}
/**
* Configure.
*
* @return void
*/
protected function configure(): void
{
parent::configure();
$this->setName('example');
$this->setDescription('A sample command');
}
/**
* Execute command.
*
* @param InputInterface $input The input
* @param OutputInterface $output The output
*
* @return int The error code, 0 on success
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$output->writeln(sprintf('<info>Hello, console</info>'));
return 0;
}
}
When i try to run php slim/app/cli.php nothing happens. I’m not sure if cli is added in the common way.
I see my created ExampleCommand but in this file i cannot create a new item for my database because he don’t know my other classes in the PHP-DI wrapper.
If i use your example of php/console.php i receive the following error:
PHP Warning: require(/Users/sam/Workspace/lemabo/slim/bin/../config/bootstrap.php): failed to open stream: No such file or directory in /Users/sam/Workspace/lemabo/slim/bin/console.php on line 30
PHP Stack trace:
PHP 1. {main}() /Users/sam/Workspace/lemabo/slim/bin/console.php:0
I’m not sure how to implement your code into my working slim 4 skeleton. can you help?
i create a copy of public/index.php and place into my bin folder
This makes no sense and could be a security issue. The index.php is only for the web access and not for the console. For the console there is already a file called: bin/console.php.