Re: Concept: "arrayable" pseudo type and \Arrayable interface

From: Date: Sun, 17 Nov 2019 23:01:46 +0000
Subject: Re: Concept: "arrayable" pseudo type and \Arrayable interface
References: 1 2 3 4  Groups: php.internals 
Request: Send a blank email to internals+get-107812@lists.php.net to get a copy of this message
> On Nov 17, 2019, at 2:27 PM, Rowan Tommins <rowan.collins@gmail.com> wrote: > Well, pretty much any method that returns array *could* be called "to array", but not > many would be good candidates for such a generic name. You might return an array structure to be > incorporated into a JSON response, or to be passed to a template renderer, or to map to database > columns, etc. > > The only case I can think of where a generic "toArray" method would make sense is if > you're creating a general-purpose "collection" or "list" object, in which > case you're probably better off directly implementing methods like map and sort, rather than > encouraging users to convert it back to a plain array. It doesn't seem like a common enough use > case to need a new language feature, when it's simple enough to write > "$foo->toArray()" without anything new. I have been pondering that objection ever since Steven Wade proposed __toArray() on the list a few months back. In part I agree with the sentiment, and in part I feel that perfection is being the enemy of the good here. But as I had no strong argument for how it could be done better I did not say anything on the matter. Consider this: __toArray() is hardly a rare case where a short name can be applied in multiple contexts. We have infinite contexts where we need to name methods for one context that might conflict with others, and so I have been agonizing for years over how to deal with this conundrum without resorting to really long method names. (As an aside, I think long method names result in harder to comprehend code, and as I have never seen a set of conventions that results in multiple programmers (almost) always choosing the same long names for the same use-cases I prefer our standards to suggest shorter names so that we can maintain more consistence across programmers.) Recently I have been experimenting with using namespaces instead of long method names, and I think using them can result in the best of both worlds and resolve your concern. Consider the following classes, each of which could have their own __toArray() method specific to their use-case: \Widgets\Widget \Widgets\JSON\Widget \Widgets\Mustache\Widget \Widgets\DbColumns\Widget With the above you can "have your cake and eat it too." Your namespace can specify the exact context for your __toArray() and thus developers who want to use that architecture can get the benefits of a __toArray() magic method. #jmtcw -Mike

« previous php.internals (#107812) next »