I figured out a way of avoiding that enemy cavalry units outflank your main infantry line in open field battles against the AI. I don't claim it's the only tactic that works ( other players might have a different tactic ):
What I avoid is forming an unique extended infantry line because enemy cavalry units ( elephants as well ) would easily get around that line. My prevention measure is having some melee infantry units behind ( Not next to ) the main infantry line. Ideally behind both ends of the main line. Specially fast spearmen units or strong swordsmen units.
When some enemy cavalry or elephants are trying to get around the main line, I order my infantry units that are behind the main line to face towards the flank from where the enemy cavalry units are coming. I try to keep them in their position. I don't chase the enemy cavalry units with my infantry units if they try to retreat because the gaps they leave might be dangerous because they could come back to take advantage of those gaps. That was a mistake I used to make when I didn't have much experience playing campaigns yet. Yoy should use only your cavalry units for chasing the retreating enemy cavalry units.
Of course you should also use your cavalry units or your elephants and your general unit as well to support your infantry units that are intercepting the enemy cavalry units in order to take them out faster.