Re: Proposal: ArraySerializable interface

From: Date: Wed, 11 Dec 2013 02:37:12 +0000
Subject: Re: Proposal: ArraySerializable interface
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-70582@lists.php.net to get a copy of this message
I think this would be a great feature. PHP already casts objects to arrays, so being able to
customize that behavior would be really helpful.

For example, Guzzle uses a similar interface to handle marshaling objects to associative arrays when
serializing requests.

-Michael

> On Dec 10, 2013, at 5:23 PM, chobie <chobieee@gmail.com> wrote:
> 
> Hi,
> 
> I've got an idea for adding common way to convert array from object:
> ArraySerializable interface and to allow the changing of existing
> array conversion mechanism.
> As an example of this change, consider the following code-snippet:
> 
>    $person = new StdClass();
>    $person->name = "John";
>    $phone = new StdClass();
>    $phone->number = "12345";
>    $person->phone = $phone;
> 
>    var_dump((array)$person);
>    #array(2) {
>    #  ["name"]=>
>    #  string(4) "John"
>    #  ["phone"]=>
>    #  object(stdClass)#2 (1) {
>    #    ["number"]=>
>    #    string(5) "12345"
>    #  }
>    #}
> 
> Currently, the implicit object to array conversion does not work
> recursively. This propose changes object to array conversion behaviour
> which implements ArraySerializable interface. specifically
> ArraySerializable::__toArray method overrides current (array) cast.
> 
>    interface ArraySerializable
>    {
>        /** @return array */
>        public function __toArray();
>    }
> 
> 
> ArraySerializable interface provides common way to convert to array
> from object. also impose conversion rule.
> 
> * __toArray() returning value excepts an array and It values only
> accepts primitive type. (long, double, string and array)
>   * do cast to array operation when the value contains object which
> implements ArraySerializable interface
>  * otherwise, raise RuntimeException.
> * __toArray() method calls implicitly when cast to array from object.
> 
> This feature improves object to portable format (like json) conversion
> mechanism.
> 
> rough propose document and patch are here:
> https://gist.github.com/chobie/7890899
> 
> I want to get feedback about this propose. If I get a good response
> I'll investigate potential issues and improve rfc and patch.
> 
> Thanks,
> Shuhei
> 
> -- 
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php
> 


Thread (10 messages)

« previous php.internals (#70582) next »