2013-05-28 18 views
3

我目前正在構建我的網站,並且我遇到了此問題。ZF2:在模板中添加登錄小部件

我想要有一個側欄和一箇中間欄的佈局。

在中間一列中,會出現內容。 在側欄中將會有登錄表單,或者如果已經記錄了「歡迎XXX」。這樣你就可以登錄每一頁。

問題是:我不知道如何創建widget/view helper來管理所有的日誌表單/歡迎信息。

目前,我有一個完整的控制器專門用於登錄,這很好。但那不符合我的需要:)。

任何想法或簡單的解釋將不勝感激:p。

謝謝!

回答

7

好的,所以我找到了解決方案。我不知道這是否是最好的,但它真的有用。 我已經在互聯網上找到了可以找到的東西。

如果你從來沒有建立一個認證服務,檢查本教程: http://samsonasik.wordpress.com/2012/10/23/zend-framework-2-create-login-authentication-using-authenticationservice-with-rememberme/

所以主要的解決方法是使用一個視圖助手。所以,在我們的版面,我們將只需要調用是這樣的:

$this->Login_widget(); 

你必須創建一個自定義視圖助手:

namespace Application\View\Helper; 

use Zend\View\Helper\AbstractHelper; 
use Application\Form\LoginForm; 
use Zend\ServiceManager\ServiceManager; 

class Loginhelper extends AbstractHelper{ 

    protected $serviceLocator; 
    protected $authService; 

    public function __invoke(){ 
     $this->authService = $this->serviceLocator->get('AuthService'); 

     if($this->authService->hasIdentity()){ 
      return $this->getView()->render('partial/login', array('getIdentity' => $this->authService->getIdentity())); 
     } 
     else{ 
      $form=new LoginForm(); 
      return $this->getView()->render('partial/login', array('form' => $form)); 
     } 
    } 

    public function setServiceLocator(ServiceManager $serviceLocator){ 
     $this->serviceLocator = $serviceLocator; 
    } 
} 

我需要得到兩件事情在這個視圖助手。

  1. 我的登錄表單,以便在我的視圖中顯示。
  2. ServiceManager(或ServiceLocator),獲取我的身份驗證服務(稱爲AuthService)。

獲取登錄表單非常簡單。只是包括它。 讓你的服務在你的Module.php中完成。

public function getViewHelperConfig() 
{ 
    return array(
     'factories' => array(
      'Login_widget' => function ($helperPluginManager) { 
       $serviceLocator = $helperPluginManager->getServiceLocator(); 
       $viewHelper = new View\Helper\Loginhelper(); 
       $viewHelper->setServiceLocator($serviceLocator); 
       return $viewHelper; 
      } 
     ) 
    ); 

}

有了這個代碼,您給服務定位到視圖助手。 現在,您可以在viewhelper中檢索您的服務。再說一遍,我不太確定它是否是最好的解決方案,但它是有效的。

您的看法助手正在工作。你只需要創建你的視圖助手的內容。 你可以返回一個部分(就像我做的那樣),或者返回你的HTML代碼(適用於小事情)。

如果使用partials,不要忘記在你的module.config.php中聲明它們。

在我的情況下,我測試用戶是否登錄。如果他是,我會打印出「歡迎傢伙」之類的東西,如果沒有,我將表單對象傳遞給我的部分,並在我的視圖中顯示。整個身份驗證過程在指定的控制器中完成。

現在,在你的佈局中,你只需要調用你的viewhelper。

<div class="container"> 
    <div id="The_login_widget_div"> 
    <?php  
     echo $this->Login_helper(); 
    ?> 
    </div> 

    <div id="main_content_div"> 
    <?php echo $this->content; ?> 
    </div>    
</div> 

就是這樣。我希望它能幫助別人。而且順便說一句,這是ZF 2.2

0

而且也許你想看到Zf2Plugin用於生成動態內容(如登錄表單)
zf2Plugin