简体   繁体   English

Zend Framework如何做到这一点,以免重复我自己

[英]Zend Framework how to do this in order to not repeat myself

I have this thing that I need in multiple places: 我在多个地方都需要这个东西:

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

These two lines: 这两行:

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

Whats the best way to do it in ZendFramework?To create a plugin or? 在ZendFramework中做这件事的最好方法是创建插件还是? I mean I want to execute it in multiple places but If I need to edit it I want to edit it in one place. 我的意思是我想在多个地方执行它,但是如果我需要编辑它,我想在一个地方编辑它。

Here is an example of an Action Helper that you can call from your controllers easily. 这是一个动作帮助器的示例,您可以轻松地从控制器调用它。

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

In order to use it, you have to tell the helper broker where it will live. 为了使用它,您必须告诉帮助代理它将在哪里生活。 Here is an example code you can put in the bootstrap to do so: 这是您可以放入引导程序中的示例代码:

// 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');

Then to use it in your controller: 然后在您的控制器中使用它:

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

It doesn't go into much detail, but Writing Your Own Helpers is helpful as well. 它没有涉及太多细节,但是编写自己的助手也很有帮助。

If you need this check in every Controller you could even set up a baseController from which you extend instead of the default one: 如果您需要在每个Controller中进行此检查,您甚至可以设置从其扩展的baseController而不是默认的baseController:

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

class IndexController extends My_Base_Controller
{ ...

Shift your init() into the base controller and you don't need to repeat yourself in every specific controller. init()移至基本控制器中,无需在每个特定的控制器中重复进行操作。

Need a varying init() in a specific controller? 需要在特定控制器中使用不同的init()吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM