Search code examples
phpcodeignitercommand-line-interfacegearmanworker

running CodeIgniter script via CLI - CI super object methods missing


I have a CodeIgniter project, and I want to invoke one of my controller methods via CLI, but normal properties & methods that are attached to the CI superobject seem to be missing?

For example, running the following script which runs perfectly fine during a normal http request produces an error:

class Worker extends MY_Controller {

    public function __construct() {
        if(php_sapi_name() !== 'cli') {
            show_404();
        }
    }

    public function test(){

        $this->load->library('some_library');

    }
}

This is the error that's returned via the CLI

  <div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">

<h4>A PHP Error was encountered</h4>

<p>Severity: Notice</p>
<p>Message:  Trying to get property of non-object</p>
<p>Filename: controllers/worker.php</p>
<p>Line Number: 21</p>

</div>PHP Fatal error:  Call to a member function library() on a non-object in /Users/casey/Documents/workspaces/vibecompass_live/application/controllers/worker.php on line 21

Fatal error: Call to a member function library() on a non-object in /Users/casey/Documents/workspaces/vibecompass_live/application/controllers/worker.php on line 21

I'm calling the script as such: $ php index.php worker test

EDIT

Additionally, this script:

class Worker extends MY_Controller {

    public function __construct() {
        if(php_sapi_name() !== 'cli') {
            show_404();
        }
    }

    public function test(){

        $CI =& get_instance();
        var_dump($CI); die();

        $this->load->library('some_library');

    }
}

Returns: NULL


Solution

  • It looks like that you have not initialized the parent class, in your controllers constructor, call the parent constructor as well:

    class Worker extends MY_Controller {
    
        public function __construct() {
            parent::__construct();
            if(php_sapi_name() !== 'cli') {
                show_404();
            }
        }