2016-03-23 52 views
0

我正在使用XML來存儲我的ACL配置,並且擴展了Zend ACL庫來解析ROLES &資源,它的工作很好。Zend Framework 2,如何緩存ACL以獲得更好的性能

下面是我ACL.XML

<?xml version="1.0" encoding="UTF-8"?> 
<permissions> 
    <roles> 
     <role name="guest" /> 
     <role name="user" inherits="guest" /> 
     <role name="admin" inherits="user" /> 
    </roles> 
    <resources> 
     <module name="account" allow="user"> 
      <controller name="account\controller\account" allow="user"> 
       <action name="login" deny="admin" /> 
      </controller> 
     </module> 
     <module name="album" allow="user"> 
      <controller name="album\controller\album" allow="user"> 
       <action name="index" allow="user" /> 
       <action name="add" allow="admin" /> 
      </controller> 
     </module> 
     <module name="application" allow="user"> 
      <controller name="application\controller\index" allow="user"> 
       <action name="index" allow="user" /> 
      </controller> 
     </module> 
    </resources> 
</permissions> 

而且我Module.php代碼,通過MvcEvent::EVENT_DISPATCH事件目前叫,

$serviceManager = $event->getApplication()->getServiceManager(); 

    $configCache = simplexml_load_file(__DIR__.'/config/acl.xml'); 

    $serviceManager->get('memcache')->setItem('cacheXml', $configCache); 

    //print_r($serviceManager->get('memcache')->getItem('cacheXml')); 

    $this->_acl  = $serviceManager->get('Acl'); 

    $this->_acl->initAcl($configCache); 

    if (! $this->_acl->_isAllowed('user', $event->getRouteMatch())) { 
       $url = $event->getRouter()->assemble(array('action' => 'index'), array('name' => 'application')); 
       $response = $event->getResponse(); 
       $response->getHeaders()->addHeaderLine('Location', $url); 
       $response->setStatusCode(302); 
       $response->sendHeaders(); 
       exit; 
    } else { 
     echo 'Access granted :) '; 
    } 

我如何可以緩存我的ACL類(部門經理)或通過任何其他意味着這段代碼變得更加持久和優化。我正在使用memcache作爲我的caching

回答

1

我的方法是創建一個ZendAclFactory並從那裏構建一個實例或從緩存中返回。

<?php 

namespace MyNamespace\Acl; 

use Zend\ServiceManager\FactoryInterface; 
use Zend\ServiceManager\ServiceLocatorInterface; 
use Zend\Permissions\Acl\Acl as ZendAcl; 
use Zend\Permissions\Acl\Resource\GenericResource; 
use Zend\Permissions\Acl\Role\GenericRole as Role; 

class ZendAclFactory implements FactoryInterface 
{ 
    private $cache; 

    public function createService(ServiceLocatorInterface $serviceLocator) 
    { 
     $this->cache = $serviceLocator->get('MyCache'); 
     $service = $this->cache->getItem('acl'); 
     if (!empty($service)) { 
      $service = unserialize($service); 
      return $service; 
     } 

     $service = new ZendAcl(); 
     //initialize you acl here.. 

     $this->cache->addItem('acl', serialize($service)); 
     return $service; 
    } 
} 
+0

謝謝@Jean會考慮它,順便說一句我現在緩存在memcache的ACL和它的工作正常,我也發佈我的方法。我也試試你 –

相關問題