How to use a helper function in a controller?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-22 04:16:28

问题


I wrote some function in app_helper file. now i need to call that function in my controller how i can do this in CAKEPHP


回答1:


You can't.*

If your functions are so universal as to be used outside of views, create them in bootstrap.php or make a custom library/class in the libs/ directory.


* You can load anything anywhere using App::import('Helper', 'NameOfHelper') or ClassRegistry::init, but you really shouldn't. The point of MVC separation is to keep your app well organized.




回答2:


App::uses('HtmlHelper', 'View/Helper');
$yourTmpHtmlHelper = new HtmlHelper(new View());

Is finally the version which works with Cakephp 2.3




回答3:


App::import('Helper', 'Forum.Common');
    $commonHelper = new CommonHelper(new View())



回答4:


You can use the helper in Controller as bellow

App::uses('YourHelper', 'View/Helper');

class yourController extends AppController {

public function index(){
    $yourHelper = new YourHelper(new View());
    $yourHelper->yourMethod();
  }

}



回答5:


If you want to use some common functions in all of your controllers like the helper does for views, you must use Components http://book.cakephp.org/2.0/en/controllers/components.html

rather using App::import('Helper', 'NameOfHelper'), this keeps the MVC standard correct and your app well organized.




回答6:


you can call helper function this way. suppose you helper is DemoHelp and call to helper function call_function() then you can use this.

App::import('Helper', 'DemoHelp');
$DemoHelp = new DemoHelpHelper();

$DemoHelp->call_function()



回答7:


You can use Component, they are stored in Controller/Component/

For example if you have Controller/Component/SomeComponent.php and want call it on the fly in single action inside controller:

$this->SomeComponent = $this->Components->load('SomeComponent');
$this->SomeComponent->someFunction();


来源:https://stackoverflow.com/questions/6450519/how-to-use-a-helper-function-in-a-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!