2
votes

I want to write my own plug in my phoenix app. The plug is to check the cookies and render the error page if cookies don't exist. Similar to the 404 error. Based on the logic, those functions below may be called:

  • put_status: set the status code of response, I set to 422.
  • put_view: My error page is located in templates/error/422.html.eex, so the ErrorView should be included.
  • render: Render the html page.
  • halt: halt the connection.
conn
|> put_status(422)
|> put_view(ErrorView)
|> render("422.html")
|> halt()

put_status and halt are in Plug.Conn. put_view and render are in Phoenix.Controller. I know that I can use the full namespace to call those functions, but it looks redundant. So I am considering import/use/alias functions as well.

For Plug.Conn, the Programming Phoenix 1.4 Book uses import​ Plug.Conn, some official plug uses alias Plug.Conn.

For Phoenix.Controller, I haven't found any example, but import could work. Is it not recommended to use Controller functions in Plug?

I am considering both the code simplify, readability and performance. Does anyone know what's the best practice for this?

Cheers

2

2 Answers

1
votes

You can import Phoenix.Controller and Plug.conn in your plug and import that plug into the controller.

defmodule DubberConnectWeb.CheckCookie do
  import Plug.Conn
  import Phoenix.Controller

  def check_cookie(conn, _opts) do
    if <check cookie existence condition..> do
     conn
     |> put_status(422)
     |> put_view(DubberConnectWeb.ErrorView)
     |> render("422.html")
     |> halt()
    else
     conn
    end
  end
end 

Then in your controller, you will just do

import DubberConnectWeb.CheckCookie
plug(:check_cookie)
0
votes

Regarding to the alias/import, neither of them causes a performance loss.

In the import doc, it says:

We use import whenever we want to easily access functions or macros from other modules without using the fully-qualified name.

And alias does it too, with the namespace included.

Therefore, both alias Plug.Conn and import Plug.Conn are good to use in the plug module.