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

ORM Events

I belive i´m sure I read a discussion here from someone to ask for an afterFetch event on ORM to decode their json-encoded rows, it sounds great, and i remember Phalcon Team did already the implementation... So, guys i am not beeing able to find the discussion here, im starting to doubt it was real... please do you tell me it is implemented or how can I use it.

Oh! its a method !

if (phalcon_method_exists_ex(object, SS("afterfetch") TSRMLS_CC) == SUCCESS) {
        phalcon_call_method_noret(object, "afterfetch");
}

But what if we make it an Event... now we can make a behavior wich listens the afterFetch (to decode) and beforeSave (to Encode) and make a behavior:


$this->addBehavior( new JSONCodec(array(
    'field' => 'config_json', 
    'property' => 'config' , 
    'assoc' => TRUE 
  )
));

You can do that already with afterFetch() and beforeSave() in your models:

https://phalcon-php-framework-documentation.readthedocs.org/en/latest/reference/models.html?highlight=afterfetch#initializing-preparing-fetched-records

From the docs:

<?php

class Robots extends Phalcon\Mvc\Model
{

    public $id;

    public $name;

    public $status;

    public function beforeSave()
    {
        //Convert the array into a string
        $this->status = join(',', $this->status);
    }

    public function afterFetch()
    {
        //Convert the string to an array
        $this->status = explode(',', $this->status);
    }
}

Instead of "explode" and "join" you can use "json_encode" and "json_decode" as you wish.

Yeah actually do this way but i suggest the behavior methos cause yo need less code ( and better ) to do that