Zend_Auth快速并随处访问UserID

I have a Zend Application with user authentication. I need the UserID in nearly every action for database queries. Certainly I want to have quick access primarily in controllers but also in view scripts.

The way I get so far:

Zend_Auth::getInstance()->getIdentity()->User_ID

How can I write a plugin or helper to provide the UserID in an easier way?

e.g. like this:

$this->User_ID

you can make property in your controller which could be set in controller constructor:

$this->_User_ID = Zend_Auth::getInstance()->getIdentity()->User_ID;

or drop it to Zend_Registry when establish and use from there.

Here is a plugin that will inject the user id into the view, or set it to null if the user has no identity.

<?php

class Application_Plugin_Identity extends Zend_Controller_Plugin_Abstract
{
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $front     = Zend_Controller_Front::getInstance();
        $bootstrap = $front->getParam('bootstrap');

        $bootstrap->bootstrap('view');
        $view = $bootstrap->getResource('view');

        if (Zend_Auth::getInstance()->hasIdentity()) {
            $view->User_ID = Zend_Auth::getInstance()->getIdentity()->User_ID;
        } else {
            $view->User_ID = null;
        }
    }
}

To enable it you can register it in a bootstrap method like this:

Zend_Controller_Front::getInstance()
->registerPlugin(new Application_Plugin_Identity());

Now from any of your view scripts, you can reference $this->User_ID and it will contain the user's id or null if not logged in.

UPDATE:

An action helper works well if you mostly want to access it from your controller.

From your controller, call $userId = $this->_helper->Identity(); to get the user ID. As a bonus, I have it assign the user id to the view as well so from the view you can call $this->User_ID

<?php

class My_Helper_Identity extends Zend_Controller_Action_Helper_Abstract
{
    protected static $_userId = null;

    public function direct()
    {
        if ($this->_userId == null) {
            $request  = $this->getRequest();
            $view     = $this->getActionController()->view;

            if (Zend_Auth::getInstance()->hasIdentity()) {
                $user_id = Zend_Auth::getInstance()->getIdentity()->User_ID;
            } else {
                $user_id = null;
            }

            $view->User_ID = $user_id;
            $this->_userId = $user_id;
            $this->getActionController()->_userId = $user_id;
        }

        return $this->_userId;
    }
}