How to use a helper function in a controller? - cakephp

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

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.

App::uses('HtmlHelper', 'View/Helper');
$yourTmpHtmlHelper = new HtmlHelper(new View());
Is finally the version which works with Cakephp 2.3

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

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

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.

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

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();

Related

Cakephp using Cache in Component

I am using Cakephp 2.3 , i want to perform lots of common calculation in my several controllers. so i write those functions in my appcontroller and i cached some datas..
but what happens is my appController will become fatty.. so i create some component to perform these actions.. i dont know my approach is right or not..? please suggest..
i want to use cache in my component, i tried this code. but nothing is cached..
public $helpers =array('Cache');
and
$result = Cache::read('fm_data', 'long');
if (!$result) {
$result =
$this->TFmStation->find('all',array('contain'=>array('TLocation',
'TLanguage','TMediaOrg','TContactPerson',
'TAddress','TFmProgram'=>array('TTargetGroup'))));
Cache::write('fm_data', $result, 'long');
}
return $result;
please help me to how to use cache in component
how to effectively use component class in cakephp in the case of more common functions in the application.. when i write these functions in appController it load all the functions so according to memory prespective, how to effectively use component
Model TFmStation is best place to have the above logic. Components are there for generic functionality like UploadComponent, EmailComponent, RecaptchaComponent etc. If your logic part have something to do with model, then it should go into that model.
A Model can be called from AppController.php in a similar fashion as you calling your Component.

In CakePHP, how do I call an AppController method from a helper?

Follow up question to: In CakePHP, where would I put a method that performs a check on the Session User?
Background: In my previous question, I was informed that the correct place to place a method such as levelCheck() which performs a semi-complicated evaluation of a user's level, and is needed in practically all my controllers, is the AppController.
Now, this method is also incredibly useful for the way I design menu layouts and other view devices. For that reason, I would like to create a helper that can make use of that method.
Problem: I recognize that it's generally frowned upon to call a controller method from the view... however there is no viable way for me to pass data to replicate the function of this method, nor do I want to replicate the method in two places (violating DRY methodology).
Question: How then do I call this method from a helper, or is there a better way to provide use of this method in the view/elements?
Put the method in AppController, also - set a variable that will save the result.
In the beforeRender callback, set the result as a viewVar.
some code:
// AppController
class AppController extends Controller
{
$levelCheckResult = null;
function levelCheck(){
$this->levelCheckResult = true/false;
}
function beforeRender(){
$this->set('levelCheckResult', $this->levelCheckResult);
}
}
that's it, now you can access it in the view.
edit
create a public function in the app_controller, and in the beforeRender(), send the app_controller itself, to the view.
class AppController extends Controller
{
function levelCheck(){
....
}
function beforeRender(){
$this->set('TheApp', $this);
}
}
// in the view
$TheApp::levelCheck();
However, please consider again the design. this kind of manipulation is strongly suggest that you should change some stuff there.
In short - the view is still backend execution of the program and not the client side, so in definition - it should and can be controlled, from the controller...
The solution I ended up using was to move the method to a component (CurrentUserComponent).
From there, it was as simple as calling the component in the head of my helper...
App::uses('CurrentUserComponent', 'Controller/Component');
And referencing the component's static method:
CurrentUserComponent::levelCheck(x,y,z);
I don't think this is entirely within the intention of the MVC pattern, but it doesn't pervert it horribly, and allows access to the method from anywhere in the application.

How to load custom plugins in CakePHP?

I'm writing a poll plugin for a website based on CakePHP. The plugin works good if I access it from its own URL (eg. myapp.com/plugin/controller) but I need to call it from different pages. I would like to include it as a widget in every page.
I'm looking for a method like $myplugin->renderPoll($pollId); but I really didn't find any information about how to instantiate the Polls class. I tried with App::import and ClassRegistry::init with no luck.
Any suggestion ?
Thank you
Looks like you are trying to create some sort of Helper to create poll cross views? I would suggest creating a Helper for that particular class. Simply create a helper in plugins/plugin_name/views/helpers/foo.php, and in each controller (or in app_controller.php) that you need it, include the helpers as $helpers = array("PluginName.Foo"); and inside your view, you should be able to use the methods defined in foo.php by calling $foo->renderPoll($pollId).
//app/plugins/plugin_name/views/helpers/foo.php
class FooHelper extends AppHelper {
var $name = "Foo";
function renderPoll($id=0) {
//...
}
}
Use Elements! They're small blocks of presentation code that need to be repeated from page to page, sometimes in different places in the layout.
Check this link out: http://book.cakephp.org/view/1081/Elements
I guess this link explains everything you need.

CakePHP - calling a component 's function from a view

How do I call a function from a component from a view? (ctp file)
Is that even a good practice to do that?
Thanks,
Tee
i suggest wrapping the component methods in a helper, and then using the usual route to access the helper.
For most components you could use something like:
App::import('Component', 'YourComponent');
$theComponent = new YourComponent();
$theComponent->yourMethod();
However, components are meant to share functionality used by controllers, so usually you should avoid calling components from views.
ALL IS POSSIBLE!
Component:
function initialize(&$controller){
$this->controller =& $controller;
$this->controller->set('YourComponent', new YourComponent());
}
View:
<?php $YourComponent->doAction() ... ?>
My opinion is it is not good practice to do that. Think of a view as something designers would work with. You want to keep your code in the models and controllers if at a possible. If it has to do with reusable view content, consider moving the controller to an element or a helper, as that is what they are intended for.
If you provide more details, we can be more specific to how to implement something if you already have a code base we can reference.
In cakephp 3
$config = new \Cake\Controller\ComponentRegistry();
$CustomComponent = new \App\Controller\Component\CustomComponent ($config);

use controller in helper

In my cakephp application i need to use my controller in helper.php. Its not working. will any one explain it with little syntax?
I really hate thinking that code can tell me how to think instead of me telling it what to do ... anyway ... here is an example for loading the controller rendering the page, and it can load any controller inside the helper.
<?Php
class HelperNameHelper extends AppHelper{
private $controller;
public function __construct(View $view, $settings = array()) {
parent::__construct($view, $settings);
$this->controller=$this->loadController();
}
protected function loadController($name=null){
if (is_null($name)) $name=$this->params['controller'];
$className = ucfirst($name) . 'Controller';
list($plugin, $className) = pluginSplit($className, true);
App::import('Controller', $name);
$cont = new $className;
$cont->constructClasses();
$cont->request=$this->request;
return $cont;
}
}
EDIT: just realiced this is such an old post :( ... this is working in cakephp 2.2.3
Helpers are not designed to have access to the controller. If you're trying to access the controller you may want to rethink your application design.
I actually had this same problem myself. I have a CakePHP 1.1 application where I was accessing the controller by passing the name of the controller as a parameter to the view. After trying to upgrade the code to work with 1.2 I realized that this was bad design. It was my first experience with CakePHP and MVC, so I chalked that up as a lesson learned.
MVC requires some up-front design to make sure that you're putting your functions in the right places (controller, model, or view).
(P.S. You can also try the #cakephp channel on irc.freenode.net)
Its an MVC.
You shouldn't use a Controller in your helper, rather use your helper in your controller.
Why would wan't to do that in the first place.
Read this:
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

Resources