Reputation: 12043
How to get the cli command that was run, from PHP?
I have this logging class
class Logger {
public function log($logMessage)
{
$this->writeLog($this->getCommand() . ' : ' . $logMessage);
}
private function getCommand()
{
//How to get the command?
//here var_dump($argv); returns NULL
}
}
This logger is being used by many classes that are run from several commands. Tow examples: process_users.php
$logger = new Logger();
$users = new Users();
foreach ($users->getUnprocessed() as $user) {
$logger->log('processing '.$user->getId());
if ($user->process()){
$logger->log('processed ' . $user->getId());
} else {
$logger->log('failed ' . $user->getId());
}
}
upload_consumer.php
$logger = new Logger();
$consumer = new UploadConsumer();
while ($message = $consumer->getNextMessage()){
$logger->log('Uploading ' . $message['name']);
$this->upload($message);
$logger->log('Finished uploading '. $message['name']);
}
So when I run php process_users.php corporate --limit 10 I want to have logs like:
php process_users.php corporate --limit 10 : processing 2554
php process_users.php corporate --limit 10 : processed 2554
php process_users.php corporate --limit 10 : processing 2555
php process_users.php corporate --limit 10 : failed 2555
And when I run php upload_consumer.php -m 100 -w I want to have logs like:
php upload_consumer.php -m 100 -w : Uploading 564sdf564sdf56sd4f.png
php upload_consumer.php -m 100 -w : Finished uploading 564sdf564sdf56sd4f.png
php upload_consumer.php -m 100 -w : Uploading sd56f4sd54f6sd6f54.png
php upload_consumer.php -m 100 -w : Finished uploading sd56f4sd54f6sd6f54.png
Is this possible?
Upvotes: 0
Views: 43
Reputation: 3288
use $argv
which will give you the arguments passed to the script and the script name try var_dump($argv); so you can see what data you're working with.
More info here http://php.net/manual/en/reserved.variables.argv.php
You can also use getopt() if you just want the cli arguments and not the script name
Remember when using within a class or a function then you will have to do global $argv
to bring it within the scope of the class or the function. Alternatively you can pass it in as a parameter rather than using global.
Upvotes: 1