2014-01-20 39 views
0

我已經在cakephp中創建了一個助手,並在AppController.php文件中定義了一個全局變量。如何在cakephp的幫助文件中使用公共變量

AppController.php

public $testVar = null; 

我想在我的幫助文件中使用這個變量。如何做到這一點?

+0

我不是在談論Auth組件。 – gautamlakum

+1

是不是和[這裏]是一樣的問題(http://stackoverflow.com/questions/6562053/passing-data-from-cakephp-component-to-a-helper)?在Helper中,你可以使用'$ this - > _View-> getVar('testVar')',在控制器中設置它()後 – lp1051

回答

0

不能使用該變量的幫手,但你可以

  1. 在AppController中,把變量會話:Session::write('currentUser', $this->currentUser)。然後,您可以使用SessionHelper在助手中訪問它:$this->Session->read('currentUser')

  2. 將變量傳遞給使用集合的視圖:$this->set('currentUser', $this->currentUser)。然後,您可以訪問視圖中的$currentUser變量,並將其作爲參數傳遞給您的幫助器。

另外,如果它是您需要登錄的用戶的ID,並且您使用的是Auth組件,則可以在會話中找到所有用戶信息。您可以在助手中訪問它,如下所示:$this->Session->read('Auth.User.id')

0

您不需要傳遞額外的變量。 直接訪問AuthComponent靜態:

echo AuthComponent::user('username'); 

注:這也注意到自由,因爲它會檢查是否存在第一(你需要手動在這裏使用數組斷言

+0

PS:如果輸入的內容太多,你可以像[Auth](https://github.com/dereuromark/tools/blob/master/Lib/Auth.php)那樣使用......來將其裁減爲'Auth :: user()'。 – mark