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
Related
I've been working on the skinny controller fat model way. Before, I used this in my controller:
$this
->find('all')
->contain(['Declarator'])
->where(['user_id' => $this->Auth->user('id')])
->order(['Declarations.created' => 'DESC']);
However, $this->Auth->user('id'), doesn't work in a model.
What other way is there to get the id from the authenticated user in a model?
What other way is there to get the id from the authenticated user in a model?
Simply pass it to a model method:
public function someModelMethod($userId, array $postData) {
// Do something here, move your code from the controller here
return $something;
}
public function someControllerAction() {
$this->set('data', $this->Model->someModelMethod(
$this->Auth->user('id'),
$this->request->data
);
}
Cake doesn't have a layer that would take the business logic so most of the time it's put in the model layer. Cake also doesn't use dependency injection so passing whole instances around like the auth object is sometimes cumbersome. Also I don't think the auth object itself should intersect with the model layer. We want to avoid tight coupling. To simplify this (also for testing) it is much easier to just pass the required values to the methods.
Mayby it's not a good idea, but in cake's model You can get users id using $_SESSION['Auth']['User']['id']
Or just use Cake\Routing\Router; at the top of your Table class and then, You can get access to session using:
Router::getRequest()->getSession()->read('Auth.User.id');
In CakePHP 2.x it's done as stated below. I'm quite sure that, even though it's not in the docs, it may be done the same way.
// Use anywhere
AuthComponent::user('id')
// From inside a controller
$this->Auth->user('id');
Source: http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-logged-in-user
Docs for version 3.x: http://book.cakephp.org/3.0/en/controllers/components/authentication.html#accessing-the-logged-in-user
i have a controller PostmustController which doesn't have any models naming Postmust. it will load a model named Post how can i do it in cakePHP.
Learned and solved it. And there is a anotherway.
You can also use this
Controller::loadModel('Post');
You can learn the detail from the following link.
Uses following array in your controller it will automatically load models in your controller.
public $uses = array('Post');
Is there any way to access the current controller or request object outside mvc in CakePHP(2.*)?
Basically I need to access the request object in a library that is designed for CakePHP but should function on its own as much as possible - in other words I'd like to avoid any unnecessary lib-specific initialization code in the controller itself to keep the.
I have written a component for this purpose but not all calls to the lib will be directly from the controller. I'd also like to avoid passing the $controller or $request variable around anywhere else but inside the lib.
I've never looked into CakePHP class loading much, but I can recall something about ClassRegistry from when CakePHP 1.3 was new. Soon after testing ClassRegistry in a controller action I found it to be empty(determined with ClassRegistry::keys() and pr()'ing directly from the class)
So, is there any friendly way to get the request object or should I resort to uglier methods?
Router::getRequest() should get you the CakeRequest instance.
Do the following code example help you?
//in Socials Controller importing SocialUsers controller
function __checkSocialUser($title, $user_id){
App::import('Controller', 'SocialUsers');
$SocialUsers = new SocialUsersController;
$SocialUsers->constructClasses();
$ourUserId = $this->Auth->user('id');
$SocialUsers->data = array('SocialUser' => array('title' => $title, 'identifier' => $user_id, 'user_id' => $ourUserId));
$result = $SocialUsers->checkUser($title, $user_id);....
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();
I am making one CakePHP project with Auth component. When I log in I got Session variable with user data. At the moment I am using this variable in controllers to pass data to the model.
$user = $this->Session->read('Auth');
$costs = $this->Posts->get_quartal_cost($user, $quartal, TRUE);
As I am using this in many controllers/models I am thinking that this is not DRY approach, so I wanted to make it better - something in AppModel(?)
Do you have some advice how to do that better?
Thanks
You could use the beforeFilter event in your AppController and do something like this:
public function beforeFilter()
{
if ( $this->Session->check('Auth') )
Configure::write('Auth', $this->Session->read('Auth'));
}
From anywhere in your controllers, models and even views, you'll be able to access it by using echo Configure::read('Auth');. See the Configuration class documentation for more information.