I've been reading about Greek and Roman tactics recently, particularly with regards to how they interacted with each other, and I started wondering how the Phalanx was ever so successful in the first place.
It seems like a manoeuvre that is extremely cumbersome and very easily outflanked by a lighter force with their need for extremely strict formations and pretty much no room for error. This makes me wonder how they prevented enemy armies from simply going around the sides of their formations and attacking from their weak flanks.
You have to remember that for most of the history of its use, the Greek phalanx was deployed against an enemy arrayed in a similar formation, phalanx against phalanx. This meant that outflanking was less of a concern than making sure the phalanx itself didn’t collapse under enemy assault. However, you are right that phalanx, in both its traditional Greek form and later Macedonian incarnation, was highly vulnerable against being flanked, especially once it had already engaged to the front, and against lighter troops more generally. This was notably displayed at the Battle of Lechaeum, where an Athenian force with an unusually high number of skirmishers routed an entire Spartan mora (500-900 men).
The Macedonian phalanx, while virtually impregnable via frontal assault, was even more vulnerable to flanking attacks. To guard against this, Philip II of Macedon established the elite units known as Hypaspists, who were equipped in much the same fashion as a Greek hoplite. They were more mobile than the phalangites and could thus be more easily deployed against potential threats to the flank. Further, the left flank of the army was typically defended by allied, usually Thessalian, cavalry, while the Macedonian cavalry was deployed in a more attacking fashion on the far right.
This was the combined arms approach of the Macedonian army, the use of which was a major factor in the success of both Philip and Alexander. The Macedonian phalanx was never intended to break the enemy army, it was the anvil upon which the enemy would be broken, pinned against the sarissas while the Macedonian cavalry wheeled around the deliver the hammer blow from the rear.
Lastly, it is worth noting that the ‘shield wall’, of which the Greek phalanx was one type, was developed and used independently by many different civilisations. For an example, the Anglo-Saxons at the Battle of Hasting fought in a shield wall that was not dissimilar to a Greek formation. The fact that it’s independent use was so widespread is a testament to its effectiveness, despite its weaknesses.