Re:PHP 8: Before and After
by dragosmocrii on Friday October 23, 2020 @03:18AM
(#24866820)
Lately I see myself abusing (???) types more often than ever. Before, I'd feel comfortable returning an array of structured data from a function. Now, I'm creating Value Objects to ensure my data is both valid and correctly used elsewhere. Kinda feels nice to get intellisense working too and knowing that the things that I'm trying to do with that VO are valid
[ Parent
| on HN ]
> Before, I'd feel comfortable returning an array of structured data from a function. Now, I'm creating Value Objects to ensure my data is both valid and correctly used elsewhere.
Same. I've written some complicated ETL/data transform processes in PHP, and used arrays because the array_* functions are so useful for manipulation.
But keeping track of what keys were available was a nightmare - especially coming back to maintain the system.
Like you I've switched to Value Objects. In many ways it's a pain (the intermediate representation that I'd stick into a new array key and pass to the next transformation - it doesn't belong on any of the objects; and PHP needs the equivalent of the array_* functions for objects) but knowing I can't use the wrong key somewhere makes it worthwhile.
PHPStan and Psalm support what they call "array shapes", basically you can treat the array keys as a type, similar to how TypeScript does it.
But your IDE could understand your code for years with:
/* @return MyObject */
Returning an array with unknown items has always been bad practice imho.Your IDE but not the PHP Interpreter, that's the advantage of making a typed return.