I want to call a controller function from a view. Is that possible in Cake PHP?
Use $this->params['controller'] to get the current controller. You can do a debug($this->params) to see other available variables. Save this answer.
The beforeFilter() method will be called for missing actions, and scaffolded actions. Controller::beforeRender() Called after controller action logic, but before the view is rendered. This callback is not used often, but may be needed if you are calling render() manually before the end of a given action.
$this is a reference to the calling object (usually the object to which the method belongs, but can be another object, if the method is called statically from the context of a secondary object). Not the most facile of definitions, but this really is stuff you're gonna have to know to navigate the code in CakePHP.
beforeRender(): beforeRendor function called after controller action logic but before the view is rendered. This function is not often used, but may be required If you are calling render() manually before the end of a given action.
It is possible via the requestAction method, but it is not recommended due to a slight performance hit. Use it wisely.
As Xr noted in the comment, using requestAction often signifies design issues (MVC separation).
Yeap use requestMethod with Caching
$out = Cache::read('savedincache');
if(empty($out)){
$out = $this->requestAction('/articles/myfunction');
Cache::write('savedincache', $out);
}
in /app/controllers/articles_controller.php
function myfunction(){
$out = $this->Article->find('all');
return $out
}
I have successfully done the following (CakePHP 2.3).
Say you have "MyController" with a public function named "functionToRun()".
From your View file:
$variable = new MyController();
$variable->functionToRun($parameter);
Note that the "$this->request" object will not be available, so if you need that data in the function, you'll have to pass it in as a parameter, and perhaps make changes to the function to allow for that.
I'm not going to argue about whether or not this is a good idea, although it should be noted that sometimes the Building is on fire, and you have to put it out yesterday. I will concede that probably the overall design should have been better, but we don't have time to rebuild Floors One through Three just because we discovered the issue when we got to Floor Five.
Given a choice of rule-breaking, I much prefer breaking this rule than the one about code duplication, which to my admittedly limited knowledge is the only remaining alternative. Code duplication leads to much worse maintenance nightmares.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With