问题
How to use Set function inside components in cake php ?
class TestComponent extends Object
{
//etc
$this->set('User', $user);
}
I am getting an error
Fatal error: Call to undefined method TestComponent::set()
How this can be corrected ?
回答1:
function startup($controller) { $this->controller = $controller }
function something() {
$this->controller->set('User',$user);
}
Cake passes the Controller reference to the startup function of a Component. You need to keep a reference in your component to use later in custom functions.
See here http://book.cakephp.org/1.3/en/view/996/Creating-Components#MVC-Class-Access-Within-Components-998
回答2:
Since most of the time Component methods are called from controllers, you can return the value from functions in controller. If you want set variables for your view layer then this can be used
$this->Controller->set('varForView',varValue);
This is because components have a class variable for the Controller instance from where it was instantiated.
来源:https://stackoverflow.com/questions/10229710/set-in-components-of-cake-php