CakePHP 2.x 将用户消息发送到元素 ('menu')

CakePHP 2.x Sending user messages to element('menu')

我想知道将数据发送到每次加载页面时出现的元素的最佳方法。

例如,一旦用户登录,我必须恢复一些关于他的信息。 User.id、User.name 等使用 SessionHelper 恢复如下:

<?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; ?>

但是,如何恢复用户收到的所有消息? 更具体地说,我应该在哪里查询数据库?在 AppController 中?在组件中 ?

感谢您的帮助:)

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 :

不是一个好主意,最好是将用户数据从auth组件设置到视图。例如,无状态身份验证将不会出现在会话中。

在您的 AppControllers beforeRender() 中只需添加:

$this->set('userData', $this->Auth->user());

并根据需要在您的视图中访问 $userData。我写了一个 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 ?

如果您需要在所有页面上使用它,也可以在 beforeRender() 回调中执行:

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

如果您只想获取特定页面上的数据,请为 Cake2 使用 requestAction(),在 Cake3 中,您可以为整个任务使用视图单元格。

并且 不要 对您的应用程序执行 link 秒:

<a href="/users/register">

相反,您应该使用 HtmlHelpers link() 方法。如果您不这样做,路由将无法工作。