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

How to “hydrate” or populate an entity from a result set in Phalcon framework?

I have a UserEntity where I set some getters and setters, ex:

class Users
{
        protected $id;
        protected $name;

        public function getId()
        {
            return $this->id;
        }

        public function setId($id)
        {
            $this->id = $id;
        }
}
...

then I have a Users model that has some find(), fetchAll() methods:

class Users extends Phalcon\Mvc\Model
{
        public function findById($id = NULL)
        {
            if(!$id) return NULL;

            return $this->find($id)->getFirst();
}

What I want is to map those entities with the result from this query.

something like this example from zend:

$entityPrototype = new TaskEntity();       <- this would be my user entity
$hydrator = new ClassMethods();            <- not sure if this exists in Phalcon
$resultset = new HydratingResultSet($hydrator, $entityPrototype);  <- do the mapping
$resultset->initialize($results);
return $resultset;

Any ideas?

Hi,

Please check this: https://docs.phalcon.io/en/latest/reference/models.html#hydration-modes

For example:

use Phalcon\Mvc\Model\Resultset;

class Users extends Phalcon\Mvc\Model
{
    public static function findById($id = NULL)
    {
        if (!$id) return NULL;

        return Users::findFirst(array(
            'conditions' => 'id = :id:',
            'bind' => array(
                'id' => $id
            ),
            'hydration' => Resultset::HYDRATE_ARRAYS
        ));
    }
}
edited Jul '14

Thanks for the response,

but I don't see where the Users entity is used here? the setters should be called,

something like:

foreach($result as $row) {
        $object = new Users();
        $object->setProperty($row);
}


5.2k
Accepted
answer

You can use hydration also with objects.

For example:

use Phalcon\Mvc\Model\Resultset;

$users = Users::find();

$users->setHydrateMode(Resultset::HYDRATE_ARRAYS);

foreach ($users as $user) {
   ...
}
edited Jul '14

ok, I was hoping that there will be a method that will do the hidration and the entity mapping for me, like

new HydratingResultSet($hydrator, $users);

but it's all good, I'll write my own

thanks