Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Using custom (extended) Resultset as default resultset

Is t possible to use custom Resultset as default? I mean model::find always return simple resultset, i want to use my custom resultset.



32.7k
Accepted
answer

You can use http://docs.phalconphp.com/en/latest/reference/models.html#using-a-custom-events-manager combined with afterFetch method. Eg:

use Phalcon\Mvc\Model,
Phalcon\Events\Manager as EventsManager;

class Robots extends Model
{

    public function initialize()
    {

        $eventsManager = new EventsManager();

        //Attach an anonymous function as a listener for "model" events
        $eventsManager->attach('model', function($event, $robot) {
            if ($event->getType() == 'afterFetch') {
                // Implement your own fetch method here
            }
            return true;
        });

        //Attach the events manager to the event
        $this->setEventsManager($eventsManager);
    }
}

Or if you want the entire resultset object, something like this:

class JsonSimple extends \Phalcon\Mvc\Model\Resultset\Simple implements \JsonSerializable
{
    public function jsonSerialize()
    {
        $arr = array();
        foreach ($this as $m) {
            $arr[] = $m->toArray();
        }

        return $arr;
    }
}

// Your code ...
use JsonSimple;
class MyModel extends \Phalcon\Mvc\Model 
{
    public function findSomenthing()
    {
        $query = "SELECT * FROM table";
        return new JsonSimple(null, $o, $o->getReadConnection()->query($query));
    }
}


1.8k
edited Jan '15

@calinrada: How can I use it with query builder?

I am thinking about something like this:

$query = $this->modelsManager->createBuilder()->from('Robots')->getQuery();
return new JsonSimple(null, $o, $o->getReadConnection()->query($query));

It throws the exception: Call to undefined function Phalcon\Mvc\Model\Query::setfetchmode()