Zend框架如何做到这一点,以便不重复我自己


Zend Framework how to do this in order to not repeat myself

我在多个地方都需要这个东西:

public function init()
{
    $fbLogin = new Zend_Session_Namespace('fbLogin'); #Get Facebook Session
    if(!$fbLogin->user) $this->_redirect('/'); #Logout the user
}

这两条线:

    $fbLogin = new Zend_Session_Namespace('fbLogin'); #Get Facebook Session
    if(!$fbLogin->user) $this->_redirect('/'); #Logout the user

在ZendFramework中最好的方法是什么?创建插件或?我的意思是我想在多个地方执行它,但如果我需要编辑它,我想在一个地方编辑它。

这里有一个Action Helper的例子,您可以很容易地从控制器中调用它。

<?php
class My_Helper_CheckFbLogin extends Zend_Controller_Action_Helper_Abstract
{
    public function direct(array $params = array())
    {
        // you could pass in $params as an array and use any of its values if needed
        $request = $this->getRequest();
        $view    = $this->getActionController()->view;
        $fbLogin = new Zend_Session_Namespace('fbLogin'); #Get Facebook Session
        if(!$fbLogin->user) {
            $this->getActionController()
                 ->getHelper('redirector')
                 ->gotoUrl('/'); #Logout the user
        }
        return true;
    }
}

为了使用它,你必须告诉助手经纪人它将住在哪里。以下是一个示例代码,您可以将其放入引导程序中:

// Make sure the path to My_ is in your path, i.e. in the library folder
Zend_Loader_Autoloader::getInstance()->registerNamespace('My_');
Zend_Controller_Action_HelperBroker::addPrefix('My_Helper');

然后在控制器中使用:

public function preDispatch()
{
    $this->_helper->CheckFbLogin(); // redirects if not logged in
}

它没有详细说明,但写你自己的帮助者也是有帮助的。

如果您需要在每个控制器中进行此检查,您甚至可以设置一个基本控制器来进行扩展,而不是默认的控制器:

class My_Base_Controller extends Zend_Controller_Action
{ 
    public function init()
    { ...

class IndexController extends My_Base_Controller
{ ...

将你的init()转换到基本控制器中,你不需要在每个特定的控制器中重复自己。

在特定控制器中需要变化的init()

class FooController extends My_Base_Controller
{
    public function init()
    {
        parent::init();
        ...