2013-07-07 25 views
3

這是我有點挑剔,但我真的很喜歡$_SESSION的作品。所以我想知道是否有一種方法可以讓我在一個數據庫中工作。我很容易創建一個超全球的,例如$_DATA['address']會返回當前登錄用戶的數據庫中保存的地址。顯而易見的問題是,當我寫入$_DATA['whatever']時,它會自動將其寫入數據庫。在C#中,這很容易,我習慣了,但在PHP中似乎沒有正常的get/set功能。有什麼方法可以讓我完成我希望做的事情?

+2

我真的*真的*認爲你不應該那樣做。全球化導致可怕的頭痛,並將你的貓放火。考慮一下調試/測試類似的東西。 – PeeHaa

+0

創建你的數據變量(或錯誤/重用其中一個超級全局變量),並使用派生的'ArrayObject'粘貼一些get/set邏輯。 – mario

+2

這是不可能的,創造你自己的superglobals。我不能評論這一點,而沒有提到存在['$ GLOBALS'](http://php.net/manual/en/reserved.variables.globals.php),但是爲了<插入本尊>的緣故* *別**。只需正確注入數據,保持封裝/可測試性/完整性,並假裝從未發生過。我保證如果你這樣做,我會忘記它。 – DaveRandom

回答

1

您可以創建一個類,並給它一些靜態輔助功能

例如:

class CurrentUser { 

    protected static $currentUser; 
    protected static function getCurrentUser(){ 
      if (!static::$currentUser){ 
       // get the current user from db and assign it to the currentUser Property 
      } 
      return static::$currentUser; 
    } 
    public static function get($property){ 
      return isset(static::getCurrentUser()->$property)?static::$currentUser->$property:null; 
    } 

    public static function set($property, $value){ 
      // make sure we have the current user 
      $user = static::getCurrentUser(); 
      if ($user){ 
       $user->$property = $value; 
       // save the user to the database. 
      } 
    } 
} 

要使用,那麼你會只是說

echo CurrentUser::get("address"); 

echo CurrentUser::set("address", "123 anystreet, anytown US 12345"); 
+0

對downvote的任何評論 – Orangepill

+0

我給你一個UP投票,因爲這實際上是一個OP的問題的合理解決方案 - 移動功能到函數或對象方法,並以這種方式調用它們。比以他描述的方式嘗試使用超全球更好。 – Richard

0

你可以使用這樣的框架Yii具有像CActiveRecord這樣的類映射到數據庫中的行。

$u = User::model()->findByPk(1); 
$u->username = "fred"; 
$u.save(); 

如果您保留對該對象的引用,則可以在每次需要時保存該記錄。

http://www.yiiframework.com/doc/api/1.1/CActiveRecord