I would like to know the best way to send data to an element which appear everytime the page is loaded.
For instance, once a user is logged in, I have to recover some informations about him. The User.id, User.name, etc. are recovered using the SessionHelper as follow :
<?php if( !$this->Session->check('Auth.User') ): ?>
<div class="taille_btn">
<a href="/users/register">
<div class="link_head">Inscription</div>
</a>
</div>
<div class="taille_btn">
<a href="/users/login">
<div class="link_head">Connexion</div>
</a>
</div>
<?php else: ?>
<div class="name_user">
<a href="/users/view/<?= $this->Session->read('Auth.User.id'); ?>">
<?= $this->Session->read('Auth.User.prenom'); ?>
</a>
</div>
<?php endif; ?>
But, how to recover all the messages the user has received ? More specifically, where am I supposed to query the database ? In the AppController ? In a Component ?
Thanks for the help :)
For instance, once a user is logged in, I have to recover some informations about him. The User.id, User.name, etc. are recovered using the SessionHelper as follow :
Not a good idea, the best is to set the user data from the auth component to the view. For example a state less auth would not be present in the session.
In your AppControllers beforeRender() simply add this:
$this->set('userData', $this->Auth->user());
And access $userData
in your view as needed. I've written an Auth helper that makes dealing with the data a little more convenient. For Cake3 it's part of this plugin.
But, how to recover all the messages the user has received ? More specifically, where am I supposed to query the database ? In the AppController ? In a Component ?
If you need it on all pages do it in the beforeRender() callback as well:
$this->loadModel('Message')
// Your logic goes into the model method
$messages = $this->Message->byUser($this->Auth->user('id'));
// Set it to the view:
$this->set('messages', $messages);
If you only want to get the data on specific pages use requestAction() for Cake2, in Cake3 you can use a view cell for the whole task.
And don't do this for links to your application:
<a href="/users/register">
Instead you should use the HtmlHelpers link() method. If you don't do that routing won't work.