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

Model data JSON response

Hello folks.

We are considering to use Phalcon as the base for our new Project. While playing arround with the Models I realized that all values inside the Model classes are strings. That is no problem but when sending out the reponses as JSON (using json_encode), numbers (and booleans) will be encoded as strings too. We used the phalcon-devtools for generating the Model classes and the datatypes are correctly added to the PHP-DocBlock:

    /**
     * @var integer
     *
     */
    protected $test1;

    /**
     * Method to set the value of field test1
     *
     * @param integer $test1
     */
    public function setTest1($test1)
    {
        $this->test1 = $test1;
    }

    /**
     * Returns the value of field test1
     *
     * @return integer
     */
    public function getTest1()
    {
        return $this->test1;
    }

We could use some custom json_encode function or set the response arrays manually by adding type casts to the getters (and setters) and setting all properties by hand.

What do you recommend to encode the model properties in their "correct datatype" in the JSON reponse? Is there a performant "Phalcon way" to achieve this? Or maybe I'am missing something obvious?

To clarify my question: Is there a way to enforce the model properties to be used as the annotated datatypes?

Thank you for your incredible work.



98.9k

Hi, actually the docblocks aren't treated as annotations by Phalcon, those are just generated to improve the code auto-completion when using an IDE that support that feature.

PDO always returns numeric values as strings (https://bugs.php.net/bug.php?id=44341) which is the database layer that Phalcon currently uses.

I think a simple way to return the correct JSON is the following:

echo json_encode(Robots::findFirst()->toArray(), JSON_NUMERIC_CHECK);
echo json_encode(Robots::find()->toArray(), JSON_NUMERIC_CHECK);

I see that PDO is the root of this issue (well, it's not really an issue - i just wondered that all methods were returning strings). Thank you very much.

Phalcon is just marvelous. I love its clear and simple API and its decoupled architecture. Keep on the good work guys. I'll flatter you a beer.



3.7k

is possible

echo json_encode(Robots::find()); for relational data



24.9k
edited Nov '14

And what about Laravel style :

return User::find(1)->toJson();

Will be implementent something like this in Phalcon? Also why not and : return User::find(1)->toXML() ;

Jusr asking, because I find these will be a good Phalcon ORM feature :)