我正在嘗試做一個代理類,允許我爲不同的sfForm設置自定義值。我必須這樣做,因爲PHP dosn't沒有多重繼承(所有的sfForm擴展了一些Base *由doctrine製作),我總是將相同的代碼複製粘貼到sfForm configure()方法。製作一個代理類
到現在爲止我做了類,但不能使它工作。我知道我必須通過引用傳遞對象,但我卡住了!
這裏是我做了什麼
class FormProxy {
private $_form;
private $_formatter;
public function __construct(sfForm &$form, $params = array()) {
$this->_form = $form;
if(count($params)>0)
$this->set ($params);
}
public function set($array = array()){
if (count($array) == 0){
return;
}
if(isset ($array['formatter'])){
$this->setFormatter($array['formatter']);
}
if(isset ($array['CSRFProtection'])){
$this->disableCSRFProtection();
}
return $this;
}
public function setForm(sfForm &$form){
$this->_form = $form;
return $this;
}
public function & getForm(){
$this->init();
return $this->_form;
}
public function getFormatter(){
return $this->_formatter;
}
public function setFormatter($formatter = null){
$this->_formatter = $formatter;
return $this;
}
private function init(){
if($this->_formatter != null){
$decorator = new sfWidgetFormSchemaFormatterLocal($form->getWidgetSchema(), $form->getValidatorSchema());
$form->getWidgetSchema()->addFormFormatter($this->_formatter, $decorator);
$form->getWidgetSchema()->setFormFormatterName($this->_formatter);
}
}
public function disableCSRFProtection(){
$this->_form->disableCSRFProtection();
}
}
我知道代理類可以是靜態的,但現在它是相同的。
編輯:
我的問題是,當我做
$proxy = new FormProxy(new ClientForm(), array(
'formatter' => 'custom',
'CSRFProtection' => false,
));
$form = $proxy->getForm();
做成FormProxy的變化似乎沒有外部施加(在$表單變量)。我認爲這是因爲我沒有很好地處理$形式的參考,但是以不同的方式嘗試了負面結果。
之後放置
$form = $this->_form;
來解決此問題爲什麼不將所有窗體所需的代碼移動到由所有窗體類繼承的BaseFormDoctrine? – Dziamid因爲:如果我做了另一個項目必須再次複製粘貼,如果升級版本相同,我不覺得它很「優雅」。我知道這不是世界的盡頭,但是如果我可以做到這一點,我會嘗試:) – Pabloks