使用户对象可用于 Zend 中的所有控制器?
我正在使用 Zend_Auth 来识别我的应用程序中的用户。 这将创建与用户对象的会话。
我的问题是如何使该对象可用于每个控制器和操作,这样我就不必每次需要该对象的数据时将其从会话中拉出?
我猜这应该在 bootstrap.php 或 index.php 中完成,但我真的不知道如何使其可用于每个控制器..所以任何代码示例将不胜感激!
谢谢!
I'm using Zend_Auth to identify a user in my application.
This creates a session with the userobject.
My question is how do I make this object available to every Controller and action, so I don't have to pull it out of the session every time I need data from this object?
I'm guessing this should be done in bootstrap.php or index.php but I don't really know how to makte it available to every controller.. so any code examples would be appreciated!
Thanks!
Bootstrap
和index.php
可能还为时过早。由于路由尚未完成,因此没有控制器可以注入您的$user
对象。我想到了几种可能性:
使用 BaseController
创建一个
BaseController
表单,所有其他控制器都可以扩展该表单。在基本控制器的init()
方法中,您可以放置分配,然后
$this->_user
将在控制器操作的任何地方可用。但很多人嘲笑 BaseController 的想法。最好使用操作助手,如下所述。
使用操作助手
创建操作助手 的
direct()
方法返回以与上面相同的方式创建的$user
对象。然后在您的控制器中,您可以以$this->_helper->user
身份访问它。确切地说,您对帮助程序类的命名以及放置它的位置取决于您使用
addPath()
方法在Zend_Controller_Action_HelperBroker
中设置的路径和命名空间。使用控制器插件
列出是为了完整性。但实际上,我认为最好的事情是上面的 Action Helper。
Bootstrap
andindex.php
are probably too early. Since routing is not yet done, there is no controller into which to inject your$user
object.Several possibilities come to mind:
Use a BaseController
Create a
BaseController
form which all your other controllers extend. In theinit()
method of your base controller, you can place your assignmentThen
$this->_user
will be available everywhere your controller actions.But many people deride the idea of a BaseController. Better to use an Action Helper, described below.
Use an Action Helper
Create an action helper whose
direct()
method returns the$user
object created in the same way as above. Then in your controllers, you can access it as$this->_helper->user
.Precisely what you name the helper class and where you place it are are dependent upon paths and namespaces you set in the
Zend_Controller_Action_HelperBroker
using theaddPath()
method.Use a Controller Plugin
Listed for completeness. But really, the best thing IMO is an Action Helper above.