Joost Berculo Tue Mar 05 03:42:31 -0500 2013

Subject: Changing the find() function in a model


One of my models (products) should only return the products of the currently logged in user, and therefore I want to change how products::find("all") works, but only for that specific model.

So basicly I want to add (prefill) a user_id to every find() for the product model. Of course I know I could do that from where I do the call, but I think that it is more safe when it is handled from a central place.

Does anyone know how to solve this problem (or if there is a better way)?

Joost Berculo Tue Mar 05 16:21:06 -0500 2013

I think I found a solution. I added the following code to my product model, and this seems to work for all the cases I tried.

public static function find() {
$args = func_get_args();
$user_id = 8; //call function to get user id;
if(isset($args[1])&&isset($args[1]['conditions'])) {
$conditions =& $args[1]['conditions'];
$conditions[0] .= " AND user_id = ?";
$conditions[] = $user_id;
} else {
if (count($args)==1) {
$args[] = array('conditions' => array("user_id = ?", $user_id));
} else {
$args[1]['conditions'] = array("user_id = ?", $user_id);
return call_user_func_array(array('parent','find'), $args);