开发者

A question about the Set() component in cakePHP

开发者 https://www.devze.com 2023-01-08 19:22 出处:网络
I am using cakePHP 1.26. In a controller, I got a function: function testing(){开发者_如何转开发

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.


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).


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));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消