How to code CakePHP components when used in Tasks? -
i have component code i'd in cakephp task, i'm not sure i'm bootstrapping controller in right way.
as simplified version, have 2 components operate fine when accessed via extended appcontroller. 1 component includes other, because calls other.
the first component:
class bigbrothercomponent extends object { var $controller = null; var $components = array('sibling'); function startup(&$controller) { $this->controller =& $controller; } function dothis() { $this->controller->loadmodel('samplemodel'); $this->sibling->dothat(); } }
the second component:
class siblingcomponent extends object { var $controller = null; function startup(&$controller) { $this->controller =& $controller; } function dothat() { /* doing stuff */ } }
to make operate command line, define shell , task. task, though i'm not sure i'm doing right.
app::import('core', 'controller'); app::import('component', 'session'); app::import('component', 'bigbrother'); class bigbrothertask extends shell { var $controller; var $bigbrother; function initialize() { $this->controller =& new controller(); // add session controller, because components access $this->controller->session->setflash(); $this->controller->session =& new sessioncomponent(); $this->controller->session->startup($this->controller); // initialise component $this->wordtotext =& new wordtotextcomponent(); $this->wordtotext->startup($this->controller); } function dothat() { $this->bigbrother->dothat(); } }
this type of task works when bigbrother component not include of it's own components, or reference other components off controller in bigbrother component. can see, i've had slight hacky thing session component.
is there better way initialize , make use of components tasks, initialize components , sub components?
i believe i've come better way, still not sure if it's best way.
firstly, components need set controller via initialize() method. ensures controller assigned if component loaded via controller or component. startup() not run components loaded other components.
therefore, components should have following
function initialize(&controller, $settings = null) { $this->controller =& $controller; }
the next step make make controller , component initialization little more dispatcher does.
app::import('core', 'controller'); class bigbrothertask extends shell { var $controller; function initialize() { $this->controller =& new controller(); $this->controller->components = array('session', 'wordtotext'); $this->controller->uses = null; $this->controller->constructclasses(); $this->controller->startupprocess(); } function dothat() { $this->controller->bigbrother->dothat(); } }
tasks don't seem have shutdown part of flow, if components need shutdowns properly, you'll have code in @ end of task function, or in shell.
Comments
Post a Comment