开发者

Codeigniter: Not sure how to make calls to this snippet of code

开发者 https://www.devze.com 2023-04-10 19:54 出处:网络
I was browsing SO and found this hosted code as a recommended way of cutting down on PHP code. https://github.com/jamierumbelow/codeigniter-base-model

I was browsing SO and found this hosted code as a recommended way of cutting down on PHP code.

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

So far, from the methods that I have figured out how to use, I love what it does and how simple it makes things.

However, in the following code:

/**
 * Get a single record by creating a WHER开发者_运维知识库E 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;
}

I'm not exactly sure how to make a call to this function. The description of what it does is exactly what I want to do.

The @params say it takes in a key and value pair for the WHERE block but I don't see any function inputs in the method signature.

Help, please?


As I'm noticing with a lot of CI code, it's strange and maintenance un-friendly.

PHP functions can accept n or more arguments (where n is the number of arguments defined in the signature)

The code makes use of func_get_args() which returns an array of arguments.

The array of arguments is then passed to the _set_where() method which passes either one or two items to the db->where() method.

A more descriptive method signature would have been

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


For future reference, and like Phil mentioned, the *_by methods pass the value through to the db->where method. This means you can use it in a variety of methods:

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

Or using an array for multiple WHERE conditions:

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

Or just the string (don't forget to escape your values!):

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

Since this question was asked, I've thoroughly updated the documentation so now it should all be a little clearer. Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消