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 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含