dsgdhtr_43654 2014-11-25 11: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 11: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.

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

报告相同问题?

悬赏问题

  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码