Issues

ZF-5974: Call to the method toJson when possible in Zend_Json_Encoder::_encodeObject

Description

When a class implement the method toJson, Zend_Json::encode (using the builtin encoder) should call this method when encoding object in the structure.

Here is a code sample :


<?php

set_include_path('/home/sylvain/src/ZendFramework/library');

require_once('Zend/Loader.php');

Zend_Loader::registerAutoload();

class JsonEncodable {
        public function toJson() {
                return '"Encodable object"';
        }
}

$struct = array(
        'encodable_object' => new JsonEncodable()
);

Zend_Json::$useBuiltinEncoderDecoder = true;
echo Zend_Json::encode($struct);

This code should return :


{"encodable_object":"Encodable object"}

Comments

Here is my implementation of the patch

Maybe it would be cleaner to add an interface (Zend_Json_Encodable) with the method toJson ?

This would only work for the internal encoder, therefore it should be implemented in such a way, that it doesnt hurt the compability with the json_encode functionality.

The use of an interface Zend_Json_Encodable is a good choice in my opinion. But we should get in touch with the ext/json author to discuss, weather and how he plans to implement nested object serialization via an interface, so that we don't drift out if a to be come php interface uses some other method instead of toJson.

@Benjamin Eberlei : That's true, and I sent an email to the author of ext/json a couple of minutes ago asking him what was his plans about it

@Sylvain Filteau: Did you recieved an answer on it?

@Benjamin Eberlei : I didn't receive an answer from him... and I don't think I will ever receive one ! ;)

Instead of limiting my feature to the builtin encoder, maybe I could add it to the magic trick used by http://framework.zend.com/manual/1.10/…

Something that could be interesting in this issue :

http://schlueters.de/blog/archives/…

This is a duplicate of ZF-9521.