Hi, I'm creating a custom find method in my AppModel: _findRandom. And I
want it to be accessible to all models, as I understand, for this to be
achieved I need "random" (as a string) to be present in a $_findMethods
array. It is set in Model class, and I thought that I can append to it in
beforeFind function in AppModel, however that did not work. Then I thought
that perhaps I should try doing it in a constructor, but that resulted in a
blank pages (no debug messages with debug level 2). So as a temporary
solution I completely redefine $_findMethods in my AppModel, bellow is how
my code looks now, but I was wondering if there's a better way to append to
that array.

---

<?php

class AppModel extends Model {
    var $actsAs = array('Containable');

    var $_findMethods = array(
        'all' => true,
        'first' => true,
        'count' => true,
        'neighbors' => true,
        'list' => true,
        'threaded' => true,
        'random' => true
    );

    function _findRandom($state, $query, $results = array()) {
        if($state == 'before') {
            if(!isset($query['limit'])) {
                $query['limit'] = 1;
            }

            # First find all ids with current conditions
            $findOptions = $query;
            unset($findOptions['limit']);
            $findOptions['fields'] = a('id');
            $list = $this->find('list', $findOptions);

            # Select random id(s)
            $list = array_keys($list);
            $resArray = array();
            for($i = 0; $i < $query['limit']; $i++) {
                $id = mt_rand(0, count($list)-1);
                array_push($resArray, $list[$id]);
            }
            $list = $resArray;

            # Add to conditions
            $primaryKey = $this->alias . '.' . $this->primaryKey;
            $query['conditions'][$primaryKey] = $list;

            return $query;
        } else {
            if(empty($results[0])) {
                return false;
            }

            return $results;
        }
    }

}

?>

Check out the new CakePHP Questions site http://cakeqs.org and help others with 
their CakePHP related questions.

You received this message because you are subscribed to the Google Groups 
"CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to
cake-php+unsubscr...@googlegroups.com For more options, visit this group at 
http://groups.google.com/group/cake-php?hl=en

Reply via email to