1
votes

I want to load component on fly in cakePHP In this example, loading dynamically RequestHandler component for json response

public function xyz() {

    $this->components[] ='RequestHandler';
    $this->Components->load('RequestHandler');
    $this->RequestHandler->initialize($this);

    $abc = array("hello","world");
    $this->set('abc', $abc);
    $this->set('_serialize', array( 'abc'));
}

error generated on initialize function shows undefined.

AMENDMENT FOR MORE CLEAR PICTURE:

public function xyz() {
    $this->components[] ='RequestHandler';
    $this->RequestHandler =  $this->Components->load('RequestHandler');
    $this->RequestHandler->initialize($this);

    $abc = array("hello","world");
    $this->set('abc', $abc);
    $this->set('_serialize', array( 'abc'));
}

I also tried

public function xyz() {

    $this->RequestHandler =  $this->Components->load('RequestHandler');
    $abc = array("hello","world");
    $this->set('abc', $abc);
    $this->set('_serialize', array( 'abc'));
}

I can't use component like this #$this->RequestHandler->getTime(); because cakephp automatic handle json respone. When I hit just above code using http://disecake.localhost/resources/xyz.json

{"code":500,"url":"/resources/xyz.json","name":"View file " /var/www/disecake/app/View/Resources/xyz.ctp" is missing."}

When I use

public $components = array( 'RequestHandler'); 
in my cotroller than output
{"abc":["hello","world"]}

I think now question is more clear.

1
"error generated on initialize function shows undefined. Thanks" You're welcome. Please read the FAQ: no thanks in questionsElias Van Ootegem
@EliasVanOotegem - FAQ is no longer among us. We now have a "Help Center".Álvaro González
Can you please edit the question and use the clipboard to copy and paste the exact error message?Álvaro González

1 Answers

12
votes

There is literally a section in the CakePHP book called "Loading Components on the fly".

CakePHP 2.x:

http://book.cakephp.org/2.0/en/controllers/components.html#loading-components-on-the-fly

CakePHP 3.x:

http://book.cakephp.org/3.0/en/controllers/components.html#loading-components-on-the-fly

(and it's done different than how you're attempting)