Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using components in Cakephp 2+ Shell

I am trying to implement a task using the cakephp shell for my application. The task involves running a long running process (hence the need to use the shell).

The function requires me to use a function inside a Component called CommonComponent

Unfortunately whenever i try to include the component i get the following error PHP Fatal error: Class 'Component' not found in /var/www/nginx-test/app/Controller/Component/CommonComponent.php

Here is the CronShell Class which is being called

class CronShell extends AppShell {
   public function main() {
        $this->out('Hello world.');      
//  $this->out(phpinfo());
    }
     public function test()
    {
         $this->out('Before Import'); 
        App::import('Component', 'Common');
        $this->out('Import complete');
        // $this->Common=ClassRegistry::init('CommonComponent');
        $this->Common =new CommonComponent();
        $this->out('Initialization complete');
        $this->Common->testCron();
         $this->out('FunctionCall complete');
        //$this->Common->saveCacheEntry("name","value");
    }
    }

The CommonComponent class is stored as app/Controller/Component/CommonComponent.php and is as follows

 class CommonComponent extends Component
{
 function testCron()
    {    
     $this->out('Hello world from Component.');
    }
 }

Any ideas?

like image 598
Sanket Gupta Avatar asked Feb 04 '12 10:02

Sanket Gupta


Video Answer


2 Answers

I had to do this recently with MTurk component I wrote. My final solution was using a lib instead of a component. Then I had the component access the lib so I could use the methods from both a component and from shell.

However, here is code that WILL allow you to load a component from a shell.

<?php
App::uses('AppShell', 'Console/Command');
App::uses('ComponentCollection', 'Controller');
App::uses('Controller', 'Controller');
App::uses('MTurkComponent', 'Controller/Component');

class ProcessCompletedTask extends Shell {
    public function execute() {
        $this->out("Processing...\n");
        $collection = new ComponentCollection();
        $this->MTurk = new MTurkComponent($collection);
        $controller = new Controller();
        $this->MTurk->initialize($controller);

        $this->MTurk->processHITs();
        $this->out("Complete\n");
    }
}
like image 93
Steve Tauber Avatar answered Sep 22 '22 15:09

Steve Tauber


What you import into the Shell should be code from within your Apps Lib

the component can also make use of the Lib code - but you'll not need to do a load of tedious stuff if you set it up right you'll make you app cleaner

if you import the component you'll need to pass it a component collection and so you'd have to make that from witin shell not that your use it (or if you do you must be doing it wrong)

like image 36
sam Avatar answered Sep 25 '22 15:09

sam