2011-04-09 49 views
0

我想在基于ZF的应用程序中授权。 在Kohana中,我可以制作类似于我的抽象控制器中的Zend的授权FW

public $auth; 
public $user; 
public function before() 
{ 
    parent::before(); 

    $this->auth = Auth::instance(); 
    $this->user = $this->auth->get_user(); 
    // $this->user is object if user was logged in or FALSE if not 
} 

如何在Zend中做同样的事情?我已阅读关于插件,并认为这是我需要的,但没有找到任何信息保存插件类文件,我应该在哪里启用它们?

回答

2

你也可以在ZF上做一些类似你在Kohana做的事情。我个人从来没有使用过Kohana的,但我的东西是ZF的版本的例子是类似于:

// assuming IndexController 
class IndexController extends Zend_Controller_Action { 

    protected $_auth; 
    protected $_user; 

    // you could also use init() here. 
    public function preDispatch() { 
     $this->_auth = Zend_Auth::getInstance(); 
     $this->_user = $this->_auth->getIdentity(); 
    } 
} 

如果你想拥有它的抽象控制器,那么你可以只创建一个(例如My_Controller_Action ),它扩展了Zend_Controller_Action。有了这个,IndexController只会扩展你的抽象控制器而不是Zend_Controller_Action。

+0

我知道我可以这样做,但...我不确定这是Zend插件的“Zend style”原因...无论如何谢谢。 – Chvanikoff 2011-04-09 10:20:20

+0

@Chvanikoff。你可以使用插件,但有时简单的解决方案是最好的。我会考虑在使用ACL时使用插件,但只有身份验证才足够。 – Marcin 2011-04-09 10:38:37

+0

其实插件的解决方案只是相同的:) Excelpt你注册它使用'$ frontController-> registerPlugin(new My_Plugin_Auth())';) – 2011-04-09 20:59:41

0

嘿!这也很简单。但是,如果你想获得授权或处理新的授权?什么都有,两个都来了。第一处理授权与数据库中的表中的证书:

$db = $this->getInvokeArg('bootstrap')->db; 
$auth = Zend_Auth::getInstance(); 

$authAdapter = new Zend_Auth_Adapter_DbTable($db); 
$authAdapter->setTableName('authLogin') 
    ->setIdentityColumn('username') 
    ->setCredentialColumn('password') 
    ->setIdentity($username) 
    ->setCredential($password); 

$result = $auth->authenticate($authAdapter); 

if ($result->isValid()) { 
    // Yeah, logged in. Do some stuff here... 
} 

这里来检查,如果用户在当前登录:

$auth = Zend_Auth::getInstance(); 

if ($auth->hasIdentity()) { 
    // User is logged in. Retrieve its identity 
    $username = $auth->getIdentity(); 
} 

希望这有助于...