The three phases of galaxy formation