zend框架的插件

时间:2014-07-23 12:21:28

标签: php zend-framework2

$ url = $ _SERVER [' SERVER_NAME'];

    if(!filter_var($url, FILTER_VALIDATE_URL)){
      return false;
    }
    return true;I need to  connect plugin CheckDomain which loaded on pre dispatch with all modules except Admin.

插件是一个类CheckDomain,可以调用它作为函数CheckDomain(),当它被调用时,它检查的域是否等于" test.example.com"

<?php 
namespace Application\Controller\Plugin;

use Zend\Mvc\Controller\Plugin\AbstractPlugin;
use Zend\Mvc\Controller\Plugin\FlashMessenger;
use Zend\Mvc\Controller\Plugin\Forward;
use Zend\Mvc\Controller\Plugin\Layout;
use Zend\Mvc\Controller\Plugin\Params;
use Zend\Mvc\Controller\Plugin\PostRedirectGet;
use Zend\Mvc\Controller\Plugin\Redirect;
use Zend\Mvc\Controller\Plugin\Url;
use Zend\View\Model\ViewModel;

 class CheckDomainPlugin extends AbstractPlugin{

  public function checkdomain()
  {

        $url = $_SERVER['SERVER_NAME'];

        if(!filter_var($url, FILTER_VALIDATE_URL)){
            return false;
       }
        return true;
    }  
}

我为除Admin之外的每个控制器调用它,但我需要使用它一次。

我的意思是可以为所有模块加载自动插件axcept admin

2 个答案:

答案 0 :(得分:0)

如果您希望“连接”每个模块,请阅读有关MVC EventsEventManager类的zf2文档。

http://framework.zend.com/manual/2.3/en/modules/zend.mvc.mvc-event.html#the-mvcevent

http://framework.zend.com/manual/2.3/en/modules/zend.event-manager.event-manager.html

以下是Application/Module.php

的一个小例子
public function onBootstrap(MvcEvent $e)
{
    $application =  $e->getApplication();
    $serviceManager = $application->getServiceManager();
    $eventManager = $application->getEventManager();
    $sharedManager = $eventManager->getSharedManager();

    // DISPATCH EVENT
    $sharedManager->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function( MvcEvent $e) use ($serviceManager) {

        $controller      = $e->getTarget();
        $controllerClass = get_class($controller);
        $moduleNamespace = substr($controllerClass, 0, strpos($controllerClass, '\\'));

        // this is the first segment from the module namespace
        // if the Admin Namespace is something like this Admin/Controller/...

        if( $moduleNamespace != 'Admin' ) {

            $CheckDomainPlugin = $serviceManager->get('ControllerPluginManager')->get('CheckDomainPlugin');
            // do something
        }
    }, 50 );
}

答案 1 :(得分:0)

如果您创建插件或任何服务,它们将可用到应用程序中的所有模块。如果有不应该使用插件的区域,请不要调用它!

如果我真的了解你的问题;我会为此使用事件监听器。如果你监听'on dispatch',你可以排除所有管理员控制器,如果你给他们一个独特的界面。

 // Module.php
 public function onBootstrap($event)
 {
   $application = $event->getApplication();
   $eventManager = $application->getEventManager()->getSharedManager();

   $eventManager->attach(
     'Zend\Mvc\Controller\AbstractActionController', 
     'dispatch', 
     function($e) {
       $target = $e->getTarget(); // The dispatched controller

       if ($controller instanceof AdminControllerInterface) {
         return;
       }
       // Do something here
     }
   );
 }