2012-05-16 14 views
-1

我現在有2個函數來構造html來顯示,這取決於數據源; 1是從database,另一個是從formpost概括一個訪問多種類型對象的函數(通過函數和數組)

function buildForm_newUser($user){ 
    $html_username = 'Username = ' . $_POST['username']; 
    $html_location = 'location = ' . $_POST['location']; 
    : // similar rows follow more than 20 times 
} 

function buildForm_exsitingUser($user){ 
    $html_username = 'Username = ' . $user->get_property('username'); 
    $html_location = 'location = ' . $user->get_property('location'); 
    : 
} 

是否有可能實現這些只有1個功能?

我試着切換源對象(即上面的$user$_POST),但後來因爲後一個函數使用指定對象的功能而被卡住,而前者沒有。另外,因爲有許多行必須訪問任一對象,所以我喜歡在處聲明新生成的變量(上例中爲$ html_ *變量),只有一個位置。這就是說,我想要這樣的事情:

function buildForm($user){ // Number and type of argument can vary 

    // Do something here to specify object type 

    $html_username = 'Username = ' . // following here, either $_POST or $user->get_property to get 'username' 
    $html_location = 'location = ' . // following here, either $_POST or $user->get_property to get 'location' 
    : 
} 

謝謝。

(也很欣賞的建議更好的標題......)

回答

0

什麼是調用這個函數?你可以簡單地接受用戶名和用戶位置作爲參數...

+0

+其他20個參數寫成,所以它不是那麼容易,但你的想法沒有錯。 – hakre

+0

對不起,我沒有看過那部分。但我認爲它並不難看:一個表單構造器應該只是建立一個表單,而不關心數據的來源。其實,我認爲在你的功能中加入一些「功能性」智能相關的代碼是錯誤的! – Sebas

1

當你正確地寫在你的問題,這兩個函數有點相同,所以你想有一個函數。

你的動力很好,你發現了一個改進的地方。怎麼做?首先,提取一個新的,第三種方法:

function buildForm_array($array) 
{ 
    $html_username = 'Username = ' . $array['username']; 
    $html_location = 'location = ' . $array['location']; 
    ... // similar rows follow more than 20 times 

} 

然後使用兩個現有的方法中是第三種方法:

function buildForm_newUser() 
{ 
    buildForm_array($_POST); 
} 

function buildForm_exsitingUser($user) 
{ 
    $array['username'] = $user->get_property('username'); 
    $array['location'] = $user->get_property('location'); 
    ... 
    buildForm_array($array); 
} 

根據您的實際代碼的樣子,這可能會導致不同的結果(這裏的例子顯然不是路的盡頭),例如,您可以根據$_POST創建一個$user對象,然後使用它通過使用現有的buildForm_exsitingUser($user)函數來生成表單。

這與使用新的第三個函數相似,但沒有創建它。所以找到模式,並減少重複的代碼。簡化。

這總是工作正在進行中,所以保持您的代碼動態變化。

+0

+1雖然你的想法並不比我理想的想法簡單,但它仍然簡化了一些事情(在這種情況下,最終輸出的工作部分不能統一,說它就像採用模式?)。等待片刻,看看有什麼其他的選擇可能出現。 – IsaacS

相關問題