简体   繁体   中英

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

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.

Need a varying init() in a specific controller?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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