As is always the case, it depends.

If you know the enemy is attacking a wall section with ladders, defending that section with a phalanx unit vs letting them up to the wall unmolested is a no-brainer. I've had Militia Hoplites hold back Hastati and worse simply because the soldiers would come over the wall surrounded by angry men. You can always order them down the stairs in the event the ladder attack falters and form them up into a regular phalanx.

Against siege towers you can still use Phalanx type troops. However, if the AI is coming up with a good melee unit, try to have two defending units to fight them. Position them to either side of the tower's drop point. This way they can attack from both sides. Yes, you can get the same effect with a single unit centered on the drop point, however, this way you have 2x the men, and one unit breaking won't lose the fight for you right away (since the attackers still have an unbroken enemy on the side not fighting a unit committed to "fight to the death"). Even if you lose that fight, it might take the attackers so long to secure the wall-top that they might have insufficient time to take the city if you're playing with a timer.

Phalanx toops aren't as good as some others in defence, but can be very useful in many circumstances. If the enemy is unable to secure the wall-tops, they aren't getting in without heavy casualties. Either they end up being drenched by the machine-gun ... er ... burning oil, or they must knock a section of wall down, meaning arrow towers and waiting defenders will make life miserable.

However, if the enemy is able to secure the wall-tops, it's relatively east to secure a gate and capture a few arrow towers. Now the enemy can march in unmolested by the wall defences, and have some arrow towers of their own to help against gate-area defenders.

But it all depends. Phalanx units make good artificial walls too, so sometimes you can get fewer casualties by simply letting the enemy in and setting up your units in the streets. Fortunately, the AI doesn't have as much luck in using missile units to counter this threat, or charging cavalry down undefended streets to hit your spear-carriers from the rear.