Re: Object and Array Literals

From: Date: Mon, 06 Jun 2011 15:15:29 +0000
Subject: Re: Object and Array Literals
References: 1 2 3  Groups: php.internals 
Request: Send a blank email to [email protected] to get a copy of this message
> Can you provide an use case and code example of how that would look?

Sure.

Here's how an ElasticSearch query currently looks in PHP:

$esQuery = new \StdClass;
$esQuery->query = new \StdClass;
$esQuery->query->term = new \StdClass;
$esQuery->query->term->name = 'beer';
$esQuery->size = 1;

// OR

$esQuery = (object)array(
    "query" => (object)array(
        "term" => (object)array(
            "name" => "beer"
        )
    ),
    "size" => 1
);

…and here's how it could look with the proposed syntax:

<?php
$esQuery = {
    "query" : {
        "term" : {
            "name": "beer"
        }
    },
    "size" : 1
};

…and here's how I'd use curl to ensure that the query I'm issuing does in fact work
with ElasticSearch:

$ curl http://localhost:9200/gimmebar/assets/_search?pretty=1
-d'{
>     "query" : {
>         "term" : {
>             "name": "beer"
>         }
>     },
>     "size" : 1
> }'

Even considering the (object)array( syntax, it's much easier to work with an
external query (as shown with curl), if we have a (nearly) JSON-compatible syntax in PHP.

Note that I *could* have written the PHP definition of $esQuery with the proposed syntax and
non-JSON compatible syntax (single quotes, for example), but I chose to write it with double quotes
because I knew I might also want to pass it to curl.

Realistically, "beer" would be in a variable (maybe {"term":
{"name": $term}}), but replacing just the variables is certainly much easier than
translating the new \StdClass syntax.

The argument for right-hand-side assignments being allowed in the proposed syntax (such as in
{'time': time()}) is still valid because I expect this syntax will be used
both for interoperating with third party services (as above), but also generally for object and
array creation without a care about third parties.

S



Thread (18 messages)

« previous php.internals (#53031) next »