2011-11-02 21 views
3

我正在查看用於創建模型類的Doctrine 2和Symfony文檔。有幾個代碼片段,其中在類中使用getProperty和setProperty,並且這些值在某個值直接分配給財產。這與典型的get/set魔術方法不同,我遇到的示例代碼沒有實現任何自定義魔術方法,所以我認爲這是由Doctrine某處處理的。自動獲取/設置函數

從我讀過的內容來看,Doctrine實現了訪問器和增變器。也許我在下載梨時錯過了一個包,或者我沒有在腳本中包含某些東西。

例如:

class User { 

    public $name; 
    public function getName() 
    { 
     // Do stuff 
    } 
} 

$user = new User(); 
$foo = $user->name; // getName is called 

注:我在尋找一個特定的原則解決。我知道這可以通過PHP完成,但我想使用Doctrine的本地函數。

編輯:更新以澄清這是如何不同於典型的獲取/設置魔術方法,並注意。

回答

6
class User { 
    private $name; 
    public function __get($property) { 
     $methodName = "get".ucfirst($property); 
     if (method_exists($this, $methodName)) { 
      return call_user_func(array($this, $methodName)); 
     } elseif (isset($this->{$property})) { 
      return $this->{$property}; 
     } 
     return null; 
    } 
    public function __set($property, $value) { 
     $methodName = "set".ucfirst($property); 
     if (method_exists($this, $methodName)) { 
      call_user_func_array(array($this,$methodName), array($value)); 
     } else { 
      $this->{$property} = $value; 
     } 
    } 
    public function getName() { 
     return "My name is ".$this->name; 
    } 
} 

$user = new User(); 
$user->name = "Foo"; 
$bar = $user->name; 
echo $bar; // "My name is Foo" 

如果有一種方法getSomethingsetSomething直接訪問屬性時,它會被調用。

正如我在this documentation page中所讀到的,正是上面的代碼做了什麼教義。但它調用方法_set('fieldName', 'value')

+0

我會嘗試用Doctrine_Record擴展我的類,看看這是否會做到這一點。 – Shroder

+0

顯然Doctrine 2是從1.x重新設計的,get/set需要手動設置。示例和文檔參考幫助我確認這一點,謝謝! – Shroder

+0

這個代碼可以在Doctrine 2中工作嗎?我真的不想手動編寫所有的getter和setter –

2

如果$name聲明public那麼這行代碼:

$foo = $user->name; 

實際訪問$name領域,其實也不是調用getName功能。

您可以使用PHP的魔術__get__set方法,自動將提供存取函數,就像這樣:

class User { 
    private $name; 
    public function __get($property) { 
     //check first to make sure that $property exists 
     return $this->$property; 
    } 
    public function __set($property, $value) { 
     //check first to make sure that $property exists 
     $this->$property = $value; 
    } 
} 

$user = new User(); 
$user->name = "Foo"; 
$bar = $user->name; 
echo $bar; //"Foo" 

你可以找到關於PHP的魔術方法here更多信息。

UPDATE:這是我想什麼主義是這樣做的:

class User { 
    private $name; 
    public function __get($property) { 
     $propertyTitleCase = mb_convert_case($property, MB_CASE_TITLE); 
     $method = "get{$propertyTitleCase}"; 
     if(method_exists($this, $method)) 
     { 
      return $this->$method(); 
     } 
     else { 
      return $this->$property; 
     } 
    } 

    public function getName() { 
     //Do Stuff 
    } 
} 
+0

你實際上並沒有在此代碼中調用getName和setName – gustavotkg

+0

我知道這一點。 'getName'和'setName'甚至沒有在我的代碼中定義。 –

+0

對,這是我對典型的get/set魔法方法的理解。我應該在我的第一篇文章中解釋這一點。我相信教義有能力添加自己的魔法,getName被自動調用,但這不適合我。所以我試圖找出原因。 – Shroder