Reputation: 359
I am building Symfony Application that use console commands. The same console command can be executed from controller thrue events, but it also can be run from terminal. How can I figure it out from where the command was run so that I can implement the user authentication if the command was run from terminal. If the command was run from controller then user already has permission to run. But if it has been run from terminal he must authenticate by username and password so that I check if he has necessary role?
Upvotes: 7
Views: 6822
Reputation: 4345
You can check if your command was run from the console or from a controller using php_sapi_name() function or PHP_SAPI constant (which is similar to php_sapi_name())
if ('cli' === PHP_SAPI) {
// command was run from the console
} else {
// command was run from a controller
}
Upvotes: 23
Reputation: 1943
The symfony Console Application has no firewall layer like the HttpKernel.
The console component was built for small 'admin like' tasks, not sth that is facing an individual user.
The whole problem could be solved by implementing a commandbus pattern.
The "command" is created by the web controller that is secured and has a user and in the CLI command (for crontab) without any security checks.
Then its passed to the command bus that handles over to the Command Handler.
The Handler contains the current logic of the execute method. The Command Object would contain any data to execute these logic == your current input arguments and options.
The Symfony Command afterwards is very slim, like just passing input args to command handler. Like it should be.
If it is a long running task it could even be offloaded from the web request to an worker queue.
Please mind the naming collision. A symfony console command !== command bus command here.
For example, you could use SimpleBus inside Symfony: https://github.com/SimpleBus
Also the recent blog post on the naming issue by @skoop: http://leftontheweb.com/blog/2016/06/18/Command-or-Controller/
Upvotes: 1