views:

37

answers:

2

Hi all,

I am using cakePHP 1.26.
In a controller, I got a function:

function testing(){
$userinfo=$this->Test->findAllByuser_id();
$this->set('userinfo',$userinfo);
}

I founf that the variable "userinfo" which contained some array data was only accessible in the testing.ctp.
to make the variable "userinfo" accessible to other .ctp files, I made use of this helper:

 $this->Session->write('userinfo', $userinfo);     

Yet, I am not sure how come the variable defined by the Set() function can't be accessed by other .ctp files but the Session can.
is there any best way of doing the same thing by using other method instead of using Session?
Please advise.

+2  A: 

Generally speaking, each method of a controller communicates with only its view (that is, the ctp file located in the folder named according to the controller name and named according to the method name). If this controller is named Tests, then variables set() in its testing() method will only be available to the ctp file identified as views/tests/testing.ctp.

To make that info available elsewhere, you either have to persist it--as you're doing in the session--or execute the controller through an "external" method like requestAction().

As a starting point, just understand that a given method of a controller directly aligns with one and only one view (again, at the risk of oversimplification).

Rob Wilkerson
+1  A: 

You can also encapsulate the function in model.

In the user model

function getUserinfo($id)
{
    return $this->findByUser_id($id);
}

Then you call it in other controller with initializing the user model

/*in another controller*/
function someAction($uid)
{
    $this->User = ClassRegistry::init("User"); // or you can use `$uses = array('User');`
    $this->set("userinfo",$this->User->getUserInfo($uid));
}
SpawnCxy