Search code examples
phpcakephpcakephp-2.4cakephp-2.x

How to create a dummy Controller in Command Shell pass to Component CakePHP 2.4.3


I use CakePHP 2.4.3

My code in Command Shell PhulyShell.php

<?php
App::uses('ComponentCollection', 'Controller');
App::uses('HopeeComponent', 'Controller/Component');

class PhulyShell extends AppShell {

    public $components = array('Hopee');

    public function initialize() {
        $collection = new ComponentCollection();
        $this->Hopee = new HopeeComponent($collection);
    }
}

HopeeComponent.php was previously written by someone else, I have no right to edit it. Inside the file it has a piece of code

public function __construct(ComponentCollection $collection, $settings = array()) {
     if($this->_Controller->request != null){
        $shortcut_app_flag = $this->_Controller->request->query('phuly_app');
     }
}

It will throw an error because there is no controller $this->_Controller

Notice Error: Trying to get property of non-object in [cakephp-2.4.3/phuly/Controller/Component/HopeeComponent.php, line 112]

I know one solution is to pass a controller to it

<?php
App::uses('ComponentCollection', 'Controller');
App::uses('HopeeComponent', 'Controller/Component');
App::uses('AppController', 'Controller');
App::uses('TestController', 'Controller');

class PhulyShell extends AppShell {

    public $components = array('Hopee');

    public function initialize() {
        $collection = new ComponentCollection();
        $collection->init(new TestController);
        $this->Hopee = new HopeeComponent($collection);
    }
}

It works and no show Notice Error, but I don't want to create a file TestController.php, I cannot use AppController.php

Is there a way to pass a dummy Controller to the Component without creating a file Controller in Shell Command?

Thanks everyone!


Solution

  • I found the answer by myself, just using Controller, I'm dumb for not noticing this

       <?php
        App::uses('ComponentCollection', 'Controller');
        App::uses('HopeeComponent', 'Controller/Component');
        App::uses('Controller', 'Controller');
        
        class PhulyShell extends AppShell {
        
            public $components = array('Hopee');
        
            public function initialize() {
                $collection = new ComponentCollection();
                $collection->init(new Controller);
                $this->Hopee = new HopeeComponent($collection);
            }
        }