dsgdhtr_43654 2014-11-25 03:35 采纳率: 100%
浏览 37
已采纳

如何知道在PHP中运行的命令?

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?

展开全部

  • 写回答

1条回答 默认 最新

  • donglisi8644 2014-11-25 03:40
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部