2011-10-06 44 views
0

我正在瀏覽SO,並發現這個託管代碼作爲削減PHP代碼的推薦方式。Codeigniter:不知道如何撥打這段代碼

https://github.com/jamierumbelow/codeigniter-base-model

到目前爲止,從我想通了如何使用方法,我喜歡它做什麼,以及如何簡單,它使事情。

然而,在下面的代碼:

/** 
* Get a single record by creating a WHERE clause by passing 
* through a CI AR where() call 
* 
* @param string $key The key to search by 
* @param string $val The value of that key 
* @return object 
*/ 
public function get_by() { 
    $where =& func_get_args(); 
    $this->_set_where($where); 

    $this->_run_before_get(); 
    $row = $this->db->get($this->_table) 
        ->row(); 
    $this->_run_after_get($row); 
    return $row; 
} 

我不完全知道如何對這個函數的調用。 它所做的描述正是我想要做的。

@params表示它需要WHERE塊的鍵和值對,但在方法簽名中沒有看到任何函數輸入。

請幫忙嗎?

+0

你想使用整個類或只是該方法? –

+0

我正在嘗試使用這個類。他有很好的指導,所以我能夠毫無問題地「安裝」課程。我可以對其他方法進行函數調用。不知道如何去調用這個方法,因爲我沒有看到任何示例代碼。 – Zigu

+0

方法成爲你的模型的一部分,只能從你自己的方法調用這些方法:'$ query = $ this-> get_by($ key,$ val);'然後'$ query-> fied;' –

回答

2

因爲我注意到很多CI代碼,這很奇怪,而且維護不友好。

PHP函數可以接受Ñ或多個參數(其中Ñ是在簽名定義參數的個數)

的代碼使用的func_get_args()它返回的參數數組。

然後將參數數組傳遞給_set_where()方法,該方法將一個或兩個項傳遞給db->where()方法。

更具描述方法簽名本來

public function get_by($key, $val = null) 
+0

混淆了使用術語密鑰......如果他說過專欄名稱,我根本不會感到困惑。 {$ this-> some_model-> get_by('some_primarykey_columnid_name','some_value'); }你如何在註釋中放置代碼括號? – Zigu

2

以供將來參考和類似菲爾提到的,*_by方法通過對db->where方法傳遞值。這意味着你可以在不同的方法使用它:

$row = $this->model->get_by('key', $value); 

或者使用多個數組,其中的條件:

$row = $this->model->get_by(array('key' => $value, 'other_key !=' => $value)); 

或者只是字符串(!不要忘記來逃避值) :

$row = $this->model->get_by('some_column = ' . $this->db->escape($value)); 

因爲這個問題被問,我已經thoroughly updated the documentation所以現在都應該更清晰一點。希望這可以幫助。