多次调用 php 脚本,具有唯一的包含

Call php script multiple times, with unique include

我正在尝试设置一个 cron 作业来更新我们所有的客户端。他们每个人在我们的网络根目录中都有自己的数据库和目录。个人调用使用此脚本:

    <?php
  include_once 'BASEPATH'.$_REQUEST['client'].'PATHTOPHPLIB';

  //Call some functions here

  //backup db
  $filename='db_backup_'.date('G_a_m_d_y').'.sql';
  $result=exec('mysqldump '.Config::read('db.basename').' --password='.Config::read('db.password').' --user='.Config::read('db.user').' --single-transaction >BACKUPDIRECTORYHERE'.$filename,$output);
  if($output=='') {
    /* no output is good */
  }else {
    logit('Could not backup db');
    logit($output);
  }
?>

我需要多次调用同一个脚本,每个脚本都有一个基于传入的客户端变量的唯一包含。我们最初为每个客户端都有一个唯一的 cron 作业,但这不再是可能的。调用此脚本的最佳方式是什么?我正在考虑创建一个新的 php 脚本,它将包含我们的客户端数组并循环遍历它 运行 这个脚本,但我不能只包含它,因为这些库将具有重叠的功能。我不考虑 cUrl,因为这些脚本不在网络根目录中。

首先,为 Symfony console component 做一个快速广告。还有其他的,但我已经使用 Symfony 一段时间了,并且倾向于它。希望你在你的项目中是 PSR-0 / Composer 的。即使你不是,这也可以给你借口做一些独立的事情。

您绝对不希望 webroot 下有这些类型的脚本。通过 apache 使它们 运行 没有任何价值,并且在内存和 运行 时间方面对它们施加限制,这在命令行 php 上下文中是不同的。

基本脚本:

<?php
  if (PHP_SAPI != "cli") {
      echo "Error: This should only be run from the command line environment!";
      exit;
  }
  // Script name is always passed, so $argc with 1 arg == 2
  if ($argc !== 2) {
      echo "Usage: $argv[0] {client}\n";
      exit;
  }
  // Setup your constants?
  DEFINE('BASEPATH', '....');
  DEFINE('PATHTOPHPLIB', '...');
  require_once 'BASEPATH' . $argv[1] . 'PATHTOPHPLIB';

  //Call some functions here

  //backup db
  $filename='db_backup_'.date('G_a_m_d_y').'.sql';
  $result=exec('mysqldump '.Config::read('db.basename').' --       password='.Config::read('db.password').' --user='.Config::read('db.user').' --single-transaction >BACKUPDIRECTORYHERE'.$filename,$output);
  if($output=='') {
  /* no output is good */
  } else {
      logit('Could not backup db');
      logit($output);
  }

调用脚本在 cron 中运行:

<?php
    // Bootstrap your master DB
    // Query the list of clients
    DEFINE('BASE_SCRIPT', 'fullpath_to_base_script_here'); 
    foreach ($clients as $client)  {
        exec('/path/to/php ' . BASE_SCRIPT . " $client");
    }

如果你想在调用者脚本中保持解耦,你可以将路径传递给备份处理脚本而不是硬连接它,如果是这样,使用相同的技术从 $argc 和 $argv 获取参数。