Refactor functions out of controllers