CakePHP Acessing full User Information - php

I am very new to CakePHP and I was just wondering if someone could help me with a couple of things.
I have a User class and an Image class.
In my users_controller.php I have the following functions
function beforeFilter(){
$this->userOb = $this->User->find();
}
function beforeRender(){
$this->set('userOb', $this->userOb);
}
This works fine and I can view the object in my view, with all the correct relations to the Image class.
But doing this overwrites the beforeFilter() and beforeRender() functions in my app_controller.php, so I try and move this functionality to my app_controller.php but I get an error (Undefined property: PagesController::$User)
Also,
$this->Auth->user();
doesn't seem to have the full object map that
$this->User->find();
returns.
So, I guess my question is how can I create a variable that is acessable in all my views, i.e it's defined in app_controller.php, that contains the current logged in Users Object and it's relations.
Thanks.

If the issue is your parent methods are being overwritten by child methods, simply call the parent method in the child, see below:
function beforeFilter(){
parent::beforeFilter();
$this->userOb = $this->User->find();
}
function beforeRender(){
parent::beforeRender();
$this->set('userOb', $this->userOb);
}

put your find result in SessionComponent so you don't have to perform a query for each request (and set variable in beforeRender). In the view you can access it with SessionHelper. $this->Auth->user(); only have the User record.

Related

Laravel 4 Model Methods access

am I doing something wrong to be able to access Methods stored in a model in a view. For Example. My User model has a method that looks like
public function isCustomer(){
if (isset($this->customer_id))
return true;
else return false;
}
When I try to access this in the view I end up with Call to a member function getResults() on a non-object.
View code is something like
#if($user->isCustomer)
Something
#endif
Is the model ONLY for database relationships between models or can I store my own class functions here as well?
The function i listed is one of the basic ones. I have quite a few more complicated functions that I would like to run from my User class but am not sure how, as i end up with the same error each time. Should they be stored in the controller?
You can store class functions there. By first glance it looks like your missing () on isCustomer. If it were me I would store that in the controller, like:
$customer = $user->isCustomer();
then pass that to the view.

CakePHP controller method not writing to the DB

I am calling one controller method from another controller's method. I can confirm that the method is being called because when I do a print_r on the passed data, I see everything I expect. My problem is that when I call $this->Log->save($this->data) nothing is written to the DB. I am a .NET developer, hence I know preciously little about cakePHP, but I know that this is the way one is supposed to save stuff to the DB, hence I am majorly stumped.
<?php
//The calling controller
App::import('Controller', 'Logs');
class othAuthComponent extends Object //I noticed this inherits from Object,
//but it doesn't seem to be a problem
{
function SomeFunction()
{
//create instance of our Logs controller as per example
$Logger = new LogsController;
$Logger->constructClasses();
$Logger->cms_addlog($user['User']['name'].' Logged in', $user['User']['id']);
}
}
?>
And the offender:
<?php
//the called controller
class LogsController extends AppController
{
function cms_addlog($note,$ba_id)
{
$this->Log->create();
$curDateTime = getdate();
$this->data['LogTime'] = $curDateTime;
$this->data['Note'] = $note;
$this->data['brandactivatorid'] = $ba_id;
//print_r($this->data);
//die();
$this->Log->save($this->data);
}
}
?>
The correct way to do this is to make the cms_addlog function part of the Log model.
Then call
$this->Log->cms_addlog($user['User']['name'].' Logged in', $user['User']['id']);
You're not supposed to call Controller actions/methods from anywhere in your code. Controller actions are meant to be directly accessed from the browser.
The clean way is to implement a addLog method in your model and call that one either from the controller, or from the component.
Please read http://book.cakephp.org/2.0/en/getting-started/cakephp-structure.html and http://book.cakephp.org/2.0/en/cakephp-overview/understanding-model-view-controller.html for further reference.

Yii extending the user doesn't seem to retain additional instance variables

I have read the tutorials on how to make a sub class of CWebUser and followed the instructions. The paths all work, and the code is getting into the right methods, however the value returned from my getter is always nil.
class PersonUser extends CWebUser {
// Store model to not repeat query.
private $_person;
// Load user model.
public function loadPerson($id=null, $duration=0)
{
$this->login($id,$duration);
$this->_person=Person::model()->findByPk(Yii::app()->user->id);
}
public function getPerson()
{
return $this->_person;
//return Person::model()->findByPk($this->id);
}
}
If I echo in the loadPerson method $this->_person->first_name after I set _person I get the value I expect. However, at any later time, if I ask for Yii::app()->user->person, the getPerson() method gets called, but $this->_person is now null. I know it's getting in there, if I uncomment the line below and have it look up the person every time, it works.
Is this an issue with Yii? I would really like to be able to cache the person object so I can reference it throughout the session without having to make more calls to the database. What am I missing??
There is no issue with Yii....
As per the documentation, CWebUser class identifies predefined variables "id" and "name" which remains persistent through out the session. Any additional variables should be used with getState() and setState() methods.
" Moreover CWebUser should be used together with IUserIdentity Class which implements the actual authentication algorithm. "
The method loadUser() is never called. And the login() call inside also doesn't make sense. A simpler implementation of getPerson() would be.
private $_person = false;
public function getPerson()
{
if($this->_person===false)
$this->_person = Person::model()->findByPk($this->id);
return $this->_person;
}

Can a site user pass their own arguments to model functions?

Are functions inside of models directly accessible by users?
Can a user pass arguments directly to a function in a model? Or, do arguments have to be passed through php?
In otherwords:
I have a model called notifications and in there a function called get_notifs($user)... I use the controller to call the function like the get_notifs($_SESSION['user_id']) (which is encrypted). I don't want someone to be able to call get_notifs() with anything but their $_session as a argument. What is the best solution?
Am I already okay?
Should I rename get_notifs() to
_get_notifs()?
Should I check the
$_SESSION['user_id'] in the method
itself?
Or, is there another better solution
than any of these?
I have a controller: ajax.php which loads the model notification
function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->library('tank_auth');
$this->load->model('notification');
$this->load->model('search');
}
function get_notifs()
{
$me = $this->session->userdata('user_id');
if ($e = $this->notification->get_notif($me))
{
...........
}
else{
echo "nothing was found wtf?";
}
.........................................................
model: notification.php
function get_notifs($user){
......
}
Your code is perfectly fine!
Am I already okay?
I Think so
Should I rename get_notifs() to _get_notifs()?
No, it's a public method so no need to make it look private.
Should I check the $_SESSION['user_id'] in the method itself?
No, this is the controller's job
Or, is there another better solution than any of these?
You only need a solution to a problem, and i don't see a problem here
it sounds liek your application may be used by people other then yourself, i.e the public developers, why would you want enforce developers to code things your way, that's going to make them upset at your application.
CI Only routes requests to a controller, the user cannot access a model or library or any other class, the route goes like so: /controller/method/param
the first segment will only ever load a controller file, the second will call the method in the param, passing any other variables such as param to that method.
Source: http://codeigniter.com/user_guide/overview/appflow.html
As you can see from the flow chart above, only the controller has access to the model's
If you'll only use it while in a session the best way would be this:
function get_notifs(){
if(!isset($_SESSION['user_id'])){
return false;
}
$user = $_SESSION['user_id'];
/* Your code here */
}
There's no point of requiring an argument when you'll only use the function with one specific variable which is also available globaly.
Edit: I don't know why you're using functions in your models. Doesn't make any sense, do you mean methods?

CakePHP: Accessing the controller or model from a view helper

I have a view helper that manages generating thumbnails for images. The images are stored using a unique ID and then linked to a file resource in the database.
I am trying to find out if it is possible for the view helper that generates these images to access the model or controller directly, as it is not possible to load the image data at any other point in the controller work flow.
I know this is a bit of a hack really, but it is easier than trying to rebuild the entire data management stack above the view.
If you had set the data in the model or controller you could access it. So you'd have to think ahead in the controller. As you said you can't load it in the controller, perhaps you need to write a specific controller function, which you can call from the view using $this->requestAction() and pass in the image name or similar as a parameter.
The only disadvantage of this is using requestAction() is frowned upon, as it initiates an entirely new dispatch cycle, which can slow down your app a bit.
The other option, which may work is creating a dynamic element and passing in a parameter into the element and have it create the image for you. Although I'm not too sure how this would work in practise.
How are you generating the thumbnails using the helper in the view if you aren't passing data into it from a controller or model? I mean if it was me, I would be setting the 'database resource' in the controller, and passing it to the view that way, then having the helper deal with it in the view. That way you could bypass this issue entirely :)
$this->params['controller'] will return what you want.
According to the ... you can put this code in a view.ctp file then open the URL to render the debug info:
$cn = get_class($this);
$cm = get_class_methods($cn);
print_r($cm);
die();
You could write a helper and build in a static function setController() and pass the reference in through as a parameter and then store it in a static variable in your helper class:
class FancyHelper extends FormHelper {
static $controller;
public static function setController($controller) {
self::$controller = $controller;
}
... more stuff
}
Then in your Controller class you could import the FancyHelper class and make the static assignment in the beforeFilter function:
App::uses('FancyHelper', 'View/Helper');
class FancyController extends AppController {
public $helpers = array('Fancy');
function beforeFilter() {
FancyHelper::setController($this);
}
... more stuff
}
And then you could access the controller from other public functions inside FancyHelper using self::$controller.
You can check the code(line ☛366 and
line ☛379) of the FormHelper, try with:
echo $this->request->params['controller'];
echo Inflector::underscore($this->viewPath);

Categories