我正在浏览SO,发现这个托管代码是减少PHP代码的推荐方法。
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块接受了一个键值对,但我在方法签名中没有看到任何函数输入。
请帮忙?
正如我在很多CI代码中注意到的那样,它很奇怪,而且维护不友好。
PHP函数可以接受n或更多参数(其中n是签名中定义的参数数(
该代码使用返回参数数组的func_get_args()
。
然后将参数数组传递给_set_where()
方法,该方法将一个或两个项传递给db->where()
方法。
一个更具描述性的方法签名应该是
public function get_by($key, $val = null)
为了将来参考,就像Phil提到的那样,*_by
方法将值传递给db->where
方法。这意味着您可以在多种方法中使用它:
$row = $this->model->get_by('key', $value);
或者将数组用于多个WHERE条件:
$row = $this->model->get_by(array('key' => $value, 'other_key !=' => $value));
或者只是字符串(不要忘记转义您的值!(:
$row = $this->model->get_by('some_column = ' . $this->db->escape($value));
既然有人问我这个问题,我已经彻底更新了文档,所以现在应该都更清楚了。希望这能有所帮助。