问题
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