CakePHP global variables in model - cakephp

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.

Related

How to get current controller action in cakephp 3.x model

I am using cakephp 3.x have put database queries in model in which i want to check the current controller action and based on that i will make my database queries.
I know i can pass controller action from my controller itself to my model function but is there a way i can just check my current controller action inside my model only so that i do not need to pass it in my multiple functions which are inside model only.
My Try -- UsersTable.php
public function initialize(array $config)
{
parent::initialize($config);
$this->table('users');
$this->primaryKey('user_id');
echo '<pre>';
print_r($GLOBALS);
exit;
}
so far if i do this, i got an array in response and in which i found this the best result out of other things in that array
[REQUEST_URI] => /5p_group/users/add
I m also trying to use this
echo '<pre>';
print_r($GLOBALS['_SERVER']['HTTP_REFERER']);
exit;
which gives me this output
http://localhost/5p_group/users/archived
so eventually i am getting the result which i want but i want another proper method which cakephp 3.x uses ..
So is there any other way or more frequent way from that i can get my current controller action ?
Any ideas will be appreciated ..
Thanks
First of all you should use the routing class in your model. So at the top you can call it like below
use Cake\Routing\Router;
And then in your initialize function you can check the params like
debug(Router::getRequest());
Or to be more specific you can use
debug(Router::getRequest()->params['action']);
I think this is the solution using cakephp classes only, though a small hack.
For more function reference you can access the cookbook at Router Class
The question was about a Model, but it shows up on Google.
When inside a view (.ctp file), use
\Cake\Routing\Router::getRequest()->getAttributes();
CakePHP 3

How to use: $this->Auth->user('id') in a model? Cakephp 3.0

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

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.

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