Codeigniter SaaS 应用程序 - 在 cli cron 作业上动态选择数据库

Codeigniter SaaS app - Dynamic database selection on cli cron job

我按照 http://anantgarg.com/2013/06/10/build-a-php-saas-app-from-scratch 中的指导在 Codeigniter 中开发了一个多租户应用程序,一切正常。现在我想向我的应用程序添加 cron 作业功能。在网上搜索时,我发现链接很少 https://www.heatware.net/programming-php/manage-cron-jobs-database-codeigniter https://glennstovall.com/writing-cron-job-in-codeigniter 并创建了一个 Codeigniter 库

class CronRunner {
var $ci;
var $ci_cron_db;
var $ci_cron_table;
public function __construct() {

    $this->ci = & get_instance();

    $this->ci->load->helper('url');
    $this->ci->load->library('user_agent');
    $this->ci->load->library('session');
    $this->ci->load->database();

    $this->ci_cron_db = $this->ci->db;
    $this->ci_cron_table = 'crn_crons';

}

private function calculateNextRun($obj) {
    return (time() + $obj->interval_sec);
}

public function run() {
    $query = $this->ci_cron_db->where('is_active', 1)->where('now() >= next_run_at OR next_run_at IS NULL', '', false)->from($this->ci_cron_table)->get();
    if ($query->num_rows() > 0) {

        $env = getenv('CI_ENV');

        foreach ($query->result() as $row) {
            $cmd = "export CI_ENV={$env} && {$row->command}";
            $this->ci_cron_db->set('next_run_at', 'FROM_UNIXTIME(' . $this->calculateNextRun($row) . ')', false)->where('id', $row->id)->update($this->ci_cron_table);
          $output = shell_exec($cmd);
            $this->ci_cron_db->set('last_run_at', 'now()', false)->where('id', $row->id)->update($this->ci_cron_table);
        }
    }
}
}

我已经使用如下所示的自定义配置文件实现了动态数据库选择

$host = $ci->input->server('HTTP_HOST');

使用 $host 将通过我的主数据库并加载客户端特定数据库。

//Database Config
$config['app_host'] = $app_db_host;
$config['app_database'] = $app_db_database;
$config['app_username'] = $app_db_username;
$config['app_password'] = $app_db_password;

在我的 database.php

$ci = get_instance();

$db['default'] = array(
    'dsn' => '',
    'hostname' => $ci->config->item('app_host'),
    'username' => $ci->config->item('app_username'),
    'password' => $ci->config->item('app_password'),
    'database' => $ci->config->item('app_database'),

至此一切正常。

现在我需要从命令行为我的 cron 作业功能实现相同的功能。当我试图从命令行而不是网络服务器调用脚本时,我无法获得 'HTTP_HOST' 值。不幸的是,直到现在我的应用程序完全依赖于 'HTTP_HOST' 用于客户选择。

有什么想法或方法可以在命令行和网络服务器上实现这一点?

提前致谢..

对于我管理的 SaaS 工具,在 crontab 中每个客户一行

1 * * * *        php /home/www/cron.php <customer-token1>
1 * * * *        php /home/www/cron.php <customer-token2>
1 * * * *        php /home/www/cron.php <customer-token3>

所以每次我有一个新客户时,它都会在 crontab 中添加一个新行,其中包含客户令牌或客户名称,如您所愿...