【问题标题】:PHP access CodeIgniter class from file executed by CLIPHP 从 CLI 执行的文件中访问 CodeIgniter 类
【发布时间】:2013-01-23 13:05:09
【问题描述】:

我有一个CI_Model 和一个名为Xray 的类。我有一个名为Pages 的控制器类,它处理我在应用程序中的所有页面。其中一页称为worker.php。我通过 CLI 使用 Supervisord 执行 worker.php

我希望能够从worker.php 访问Xray 的函数,但不能通过命令行(执行worker.php 后我不会使用命令行)。

【问题讨论】:

  • “普通页面”是指控制器类? X 射线是“Xray_model”吗?你的语言有点不清楚 - 你能解释一下你的结构吗?
  • 我更明确了我的意图

标签: php codeigniter class command-line-interface


【解决方案1】:

将 Xray 作为模型或库加载,以更合适的方式加载,并正常访问

class Pages extends CI_Controller {

    function worker()
    {
        $this->load->library('Xray');
        echo $this->xray->my_func();
    }

}

【讨论】:

  • 我可以从浏览器访问 worker.php 文件并访问任何与 CI 相关的内容,但是当它从 CLI 执行时,我会收到类似 PHP Fatal error: Using $this when not in object context 的错误。那么有什么不同呢?就像 worker.php 因加载方式而与其他所有内容分离。
【解决方案2】:

以下是在外部加载的脚本中包含 CodeIgniter 功能所需的代码:

ob_start();
include('/path/to/your/index.php');
ob_end_clean();

$ci =& get_instance();
$ci->load->model('xray');

所以问题是没有CI 实例,因此不会加载任何内容。

取自Ellislabs Forums

【讨论】:

    【解决方案3】:

    问题是$this 是当前null

    我只是先调用父母的构造函数:

    function __construct()
    {
       parent::__construct();
    }
    

    如果您检查parent,您将看到class CI_Controller,然后function __contruct() 将帮助您正确启动。

    现在你的$this 是一个对象,你可以这样做

    $this->config->load()$this->load->library('Xray');

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多