We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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.



51.1k
Accepted
answer

You can use https://docs.phalcon.io/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));
    }
}


2.5k
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()