r/PHP • u/[deleted] • Jun 29 '14
Stop abusing arrays in PHP
http://nomad.so/2014/06/stop-abusing-arrays-in-php/7
u/ivosaurus Jun 29 '14 edited Jun 30 '14
If this was another language, they would be dictionaries, or hashes, or maps, and it would be a perfectly normal use of them.
The problem is the name PHP gave to this data structure in the first place. It's hardly the implementation one would normally associate with what's referred to as an "array" in most languages / data structures courses or CS in general.
If there's semantic behaviour that's useful to associate to the array's (/dictionary's) contents, then yes, it can be a great idea to map them onto objects, but otherwise keeping them in a structured recursive format is just fine; a lot of data looks like this anyway.
In short, you may as well say that JSON is an evil data transport format, because that's probably the most common expression of this sort of data seen in this day and age.
1
u/Salamok Jun 30 '14
Oh shit I think you just prompted the guy to write a 5 page article on why SOAP is the shit and JSON is for 15 year olds.
15
u/rq60 Jun 29 '14
TLDR: Arrays are evil, let me show you how to use Iterators!! That return an ArrayIterator...
15
u/atw527 Jun 29 '14
My problem here is that arrays are always used where objects should be!
Stopped reading the article at that point.
2
u/MorrisonLevi Jun 30 '14
I started skimming at this point.
To sum up my thoughts: if you are dumping JSON from a database then use arrays and json_encode them; else consider using classes.
5
u/Xinil Jun 29 '14
I would have appreciated more examples of an array turned in to an object. The example he used were more or less psuedo code and didn't implement what he said it could. I use arrays a lot, probably too much, so I'd love concrete examples for everyday problems.
8
u/willmorgan Jun 29 '14
What this man is advocating is essentially replicating that same structure, but putting a load of classes on top of it to make it more complicated.
At a very primitive level, "abusing" arrays in the article's example is simpler and less time consuming than this method. Only in large applications is it worth going to the extreme of creating a collection / iterator class per "dimension" of the array... and at that point, a good programmer would consider alternatives to managing so much data at once, anyway.
In fact, in a way, this article is a bit of a straw man - doesn't this gigantic array look more like a JSON document to you? Something you'd get back from an API, perhaps? Hmm.
3
u/chuyskywalker Jun 30 '14
What this man is advocating is essentially replicating that same structure, but putting a load of classes on top of it to make it more complicated. Only in large applications is it worth going to the extreme of creating a collection / iterator class per "dimension" of the array
To expand:
In a simple, narrow view, all this extra code is more complicated. Implementing it takes time, a not-small bit of extra code, and is a more advanced topic.
That said, when your codes base starts getting larger, having clear interfaces/methods on collections (and ultimately getters/setters on the returned instances) is far easier for a larger team to develop upon. Basically, there's very little room for error -- if you call a wrong
method()PHP will fatal you. If you call a bad$array['thing']you get a plain notice which, sadly, can be pretty easy to, well, not notice). And, of course, if you have an IDE you get full code completion which makes is bloody obvious that you've made a code error (red squiggle underlines) and even easier down the road if you, god forbid, ever need to refactor your data objects. (IE: Have fun searching for that array key of "config" throughout a codebase.)For your small home grown project, butcher arrays as deep as you want. If you want multiple people to work on a codebase day in and out, put better structure behind your data objects -- don't make me have to alt tab to the magic list of what's in the array every time I can't recall what library 56 of 738 wants me to call
personvalue. (Was thatperson? Oruser? Hrm, maybeuserInfo? Ugh...)0
u/-Mahn Jun 29 '14
It's not just simpler and less time consuming, a simple multidimensional array is also much more efficient than a set of objects and a collection both in terms of memory and performance. This rarely makes a significant difference unless the data is huge, but still.
3
u/aichibuchi Jun 29 '14
Any application sufficiently large for that to actually make a performance difference needs to be well-structured, which probably means not using massive multidimensional arrays, right? Also, I'm pretty sure performance is incredibly inexpensive these days. Certainly cheaper than spending engineering time maintaining something poorly structured.
2
u/00Davo Jul 09 '14 edited Jul 09 '14
Reiterating this snippet's simplicity
$stockedFish = $ponds->getTotalStockNumber();relative to something like
foreach ($ponds as $pond)
{
if (isset($pond["fishBreeds"]))
{
foreach ($pond["fishBreeds"] as $breed)
{
if (isset($breed["number"]))
{
$stockedFish += $breed["number"];
}
}
}
}seems, well, disingenous. getTotalStockNumber() won't just magically work without being implemented somewhere, and its implementation is almost certainly going to involve foreach loops much like those in the second sample.
By the same token, you could as easily make a comparison like this:
With OO design, you often end up with dozens of extraneous classes to implement something that would be straightforward in procedural code. Here's what would be a simple calculation, implemented in classes:
class PondsCollection implements IteratorAggregate { private $collection = array(); public function getIterator() { return new ArrayIterator($this->collection); } public function add($pond) { $this->collection[] = $pond; } public function getTotalStockNumber() { $sum = 0; foreach($collection as $pond) { $sum += $pond->getTotalStockNumber(); } return $sum; } } class StockDataCollection implements IteratorAggregate { private $collection = array(); public function getIterator() { return new ArrayIterator($this->collection); } public function add($stockdata) { $this->collection[] = $stockdata; } public function getTotalStockNumber() { $sum = 0; foreach($collection as $fish) { $sum += $fish->number; } return $sum; } } class Pond { public $name; public $size; public $pegs; public $amenities; public $fishBreeds; public function getTotalStockNumber() { return $fishBreeds->getTotalStockNumber(); } } class StockData { public $name; public $number; public $date; }Wouldn't it be a lot simpler to do this?
$stockedFish = getTotalStockNumber($ponds);
Of course, both comparisons are equally misleading, and in fact neither actual implementation is significantly more complex. The same fundamental techniques of functional abstraction are applicable regardless of paradigm here.
1
u/moonpi3 Jun 30 '14
I like the idea of avoiding the use of arrays as data types. I usually turn these into objects. Otherwise, I use Dictionary, Enum, Collections and Tuple classes in PHP when appropriate. It's a little more overhead, but it's easier code to maintain.
1
u/DancesWithNamespaces Jul 02 '14
I get the point you're trying to make, but I don't think you quite grasp the entire concept you're trying to explain either.
Arrays are often used when classes would be better served for the purpose, but sometimes arrays are a better choice in the scope of the function they're being used in.
Your entire article could have been replaced with the sentence from your conclusion: "Arrays are not evil but should only be used when a collection of data has no associated behaviour." and made much more meaningful sense.
0
u/bulbishNYC Jun 29 '14
Guys in their teens are wannabe hackers - the more unreadable my code the better. Guys in their 30's are seasoned pros - keep everything simple a retard can read & maintain it. 20's - middle ground, pattern over-engineering, pimp-my-github phase.
2
u/mattaugamer Jun 29 '14
I'm 37. Approaching about 15 years in this industry. And I think you're full of shit.
More specifically, I think you're partially right. Older, senior devs care more about maintainability. But the point of what this article is saying is to advocate more maintainable coding.
In my experience older developers fall into two camps: seasoned veterans who know the value of maintainability while using appropriate abstractions and patterns, and ossified older devs who don't want to learn new things and refuse to improve their skills.
Be careful not to be the latter, while thinking you're the former.
1
u/zendopeace Jun 29 '14
Pretty much this. Real programmers who have been out there and doing real work dont care so much for patterns and the latest buzz word, we just get it done. Arrays are useful, we use them. Objects are useful, we use them too. Theres no point getting so emotional about it all.
-1
0
u/adrianmiu Jun 29 '14
"Arrays are not evil but should only be used when a collection of data has no associated behaviour." On the other hand $user->getName() is not a behaviour.
The reason people use objects when they can use arrays is that the IDE's autocompletion makes it so you don't need to memorize the structure of the array.
2
Jun 30 '14
Being able to enforce an interface is a good enough reason for me. I couldn't care less about IDE sorcery.
-6
u/jasonlotito Jun 29 '14
ITT: PHP script kiddies complaining about someone bad mouthing their arrays.
2
0
u/Thatonefreeman Jun 30 '14 edited Jun 30 '14
Yes lets take a simple data model and make it needlessly more complicated by adding layers to it. Know what the learning curve is of an array? Zip. None. Look at it and you know it. You're going to spend more time writing up your classes than you will building a simple function to parse arguments into an existing structure. Plus littering your code with objects will only serve to lengthen your already short time with educating new developers on your code.
Arrays are meant to be "abused" because that's one of PHP's greatest features. There is a time and place for arrays and objects of course, its subjective, but one should not conduct a witch hunt on every array in existence to justify itself.
1
-2
u/stesch Jun 29 '14
I guess Lerdorf's talk about OO being slow had made a huge impression on PHP users.
1
Jul 07 '14
This is rich coming from Lerdorf. PHP is one of the worst designed, poorly performing languages ever.
9
u/jasonlotito Jun 29 '14
I've never seen a case were OO was the bottleneck. You literally have to remove networking from the equation to make it have any impact.
1
u/stesch Jun 30 '14
I think the problem in Lerdorf's talk was that he was trying big frameworks. And profiled and optimized the absolute shit out of it. Including tracing Apache httpd.
27
u/dont_ban_me_please Jun 29 '14
Oh fuck this guy. PHP arrays are powerful and flexible and simple to create and use. They just get the job done. That's what PHP does, it just fucking gets the job done. That's what has made it so popular and that is why this guy is completely wrong.