↓ Ir para o conteúdo principal

← todas as notas

📎 Webclip

Sharing Functions Between Phoenix Controllers

The post says Phoenix applications often need shared controller functions to avoid duplicating code. It places helper functions in a helpers.ex file under web/controllers and shows that, instead of importing them in each controller, the shared import can be added in web/web.ex.

Reading notes
#

  • Phoenix controllers often need shared functions to keep code DRY.
  • Helper functions can live in a helpers.ex file inside web/controllers.
  • Importing helpers in each controller works, but repeats the same line.
  • The shared controller definitions are in web/web.ex.
  • use MyApp.Web, :controller calls the controller/0 function in web/web.ex.
  • The use call triggers the using macro on MyApp.Web with :controller.
  • using calls apply/3, which expands the quoted code from controller/0 into the controller.
  • Adding another import line to controller/0 makes the helper module available in all controllers.
  • The same technique can extend functionality to views, channels, router, and models.