[英]Zend Framework how to do this in order to not repeat myself
我在多個地方都需要這個東西:
public function init()
{
$fbLogin = new Zend_Session_Namespace('fbLogin'); #Get Facebook Session
if(!$fbLogin->user) $this->_redirect('/'); #Logout the user
}
這兩行:
$fbLogin = new Zend_Session_Namespace('fbLogin'); #Get Facebook Session
if(!$fbLogin->user) $this->_redirect('/'); #Logout the user
在ZendFramework中做這件事的最好方法是創建插件還是? 我的意思是我想在多個地方執行它,但是如果我需要編輯它,我想在一個地方編輯它。
這是一個動作幫助器的示例,您可以輕松地從控制器調用它。
<?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;
}
}
為了使用它,您必須告訴幫助代理它將在哪里生活。 這是您可以放入引導程序中的示例代碼:
// 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');
然后在您的控制器中使用它:
public function preDispatch()
{
$this->_helper->CheckFbLogin(); // redirects if not logged in
}
它沒有涉及太多細節,但是編寫自己的助手也很有幫助。
如果您需要在每個Controller中進行此檢查,您甚至可以設置從其擴展的baseController而不是默認的baseController:
class My_Base_Controller extends Zend_Controller_Action
{
public function init()
{ ...
class IndexController extends My_Base_Controller
{ ...
將init()
移至基本控制器中,無需在每個特定的控制器中重復進行操作。
需要在特定控制器中使用不同的init()
嗎?
class FooController extends My_Base_Controller
{
public function init()
{
parent::init();
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.