DEV Community

Cover image for Mastering Phoenix Framework - Part 1
Rushikesh Pandit
Rushikesh Pandit

Posted on • Updated on

Mastering Phoenix Framework - Part 1

Hi All,

This blog is dedicated to the mix tasks that we use very often while developing applications using Phoenix Framework.

Before that, please have a look at this if you are not aware of How Phoenix works and Lifecycle of Phoenix requests.

Here, I am assuming that you already have the Elixir and Phoenix framework installed on your local machine.

So, without wasting further time, let's start with our today's topic.

We will use a tool called as mix to generate the Phoenix app. Mix is a build tool that ships with Elixir that provides tasks for creating, compiling, testing your application, managing its dependencies and much more;

- Create a new project

mix phx.new {PROJECT_NAME}

In the above command, we are asking the mix tool to use a task named phx.new and passing {PROJECT_NAME} as a parameter.

There are many tasks in the mix tool which we can utilise to ease our development. You can get the list of such useful tasks as follows

$ mix help --search "phx"
mix local.phx          # Updates the Phoenix project generator locally
mix phx                # Prints Phoenix help information
mix phx. digest         # Digests and compresses static files
mix phx.digest.clean   # Removes old versions of static assets.
mix phx.gen.auth       # Generates authentication logic for a resource
mix phx.gen.cert       # Generates a self-signed certificate for HTTPS testing
mix phx.gen.channel    # Generates a Phoenix channel
mix phx.gen.context    # Generates a context with functions around an Ecto schema
mix phx.gen.embedded   # Generates an embedded Ecto schema file
mix phx.gen.html       # Generates controller, views, and context for an HTML resource
mix phx.gen.json       # Generates controller, views, and context for a JSON resource
mix phx.gen.live       # Generates LiveView, templates, and context for a resource
mix phx.gen.notifier   # Generates a notifier that delivers emails by default
mix phx.gen.presence   # Generates a Presence tracker
mix phx.gen.schema     # Generates an Ecto schema and migration file
mix phx.gen.secret     # Generates a secret
mix phx.gen.socket     # Generates a Phoenix socket handler
mix phx.new            # Creates a new Phoenix application
mix phx.new.ecto       # Creates a new Ecto project within an umbrella project
mix phx.new.web        # Creates a new Phoenix web project within an umbrella project
mix phx.routes         # Prints all routes
mix phx.server         # Starts applications and their servers

Enter fullscreen mode Exit fullscreen mode

We will cover some Phoenix Mix tasks, except phx.new, phx.new.ecto, and phx.new.web, which are part of the Phoenix installer. You can learn more about them or any other task by calling mix help TASK.

- mix phx.gen.html

Phoenix can generate the necessary code for a complete HTML resource, including Ecto migrations, contexts, controllers, views, and templates, saving significant time.

To use this feature, run the mix phx.gen.html task with the following arguments: context module name, schema module name, resource name, and a list of column_name:type attributes. Ensure the module names follow Elixir's capitalization rules.

$ mix phx.gen.html Blog Post posts body:string word_count:integer
Enter fullscreen mode Exit fullscreen mode

When mix phx.gen.html is done creating files, it helpfully tells us that we need to add a line to our router file as well as run our Ecto migrations.

Add the resource to your browser scope in lib/hello_web/router.ex:

    resources "/posts", PostController

Remember to update your repository by running migrations:

    $ mix ecto.migrate
Enter fullscreen mode Exit fullscreen mode

If we don't want to create a context or schema for our resource we can use the --no-context flag. Note that this still requires a context module name as a parameter.

$ mix phx.gen.html Blog Post posts body:string word_count:integer --no-context
Enter fullscreen mode Exit fullscreen mode

It will tell us we need to add a line to our router file, but since we skipped the context, it won't mention anything about ecto.migrate.

Add the resource to your browser scope in lib/hello_web/router.ex:

    resources "/posts", PostController
Enter fullscreen mode Exit fullscreen mode

Similarly, if we want a context created without a schema for our resource we can use the --no-schema flag.

$ mix phx.gen.html Blog Post posts body:string word_count:integer --no-schema
Enter fullscreen mode Exit fullscreen mode

It will tell us we need to add a line to our router file, but since we skipped the schema, it won't mention anything about ecto.migrate.

- mix phx.gen.json

Phoenix allows for generating all the necessary code to set up a complete JSON resource, including Ecto migrations, schemas, controllers with required actions, and views. This command excludes template creation.

To use this feature, use the mix phx.gen.json task with these arguments: context module name, schema module name, resource name, and a list of column_name:type attributes. Ensure the module names adhere to Elixir's module naming conventions with proper capitalization.

$ mix phx.gen.json Blog Post posts title:string content:string
Enter fullscreen mode Exit fullscreen mode

When mix phx.gen.json is done creating files, it helpfully tells us that we need to add a line to our router file as well as run our Ecto migrations.

Add the resource to the "/api" scope in lib/hello_web/router.ex:

    resources "/posts", PostController, except: [:new, :edit]

Remember to update your repository by running migrations:

    $ mix ecto.migrate
Enter fullscreen mode Exit fullscreen mode

Same as mix phx.gen.html, mix phx.gen.json also supports --no-context, --no-schema, and other parameters.

- mix phx.gen.context

If you only need a context without generating a complete HTML or JSON resource, you can use the mix phx.gen.context task. This command generates a context, a schema, a migration, and a test case.

To use mix phx.gen.context, provide the following arguments: context module name, schema module name, resource name, and a list of column_name:type attributes. Ensure the module names follow Elixir's module naming conventions with proper capitalization.

$ mix phx.gen.context Accounts User users name:string age:integer
Enter fullscreen mode Exit fullscreen mode

- mix phx.gen.schema

If you're not interested in generating a complete HTML/JSON resource and only need to create a schema with its migration, you can use the mix phx.gen.schema task.

To use mix phx.gen.schema, provide the following arguments: the module name of the schema (which can be namespaced), the resource name, and a list of column_name:type attributes. This command efficiently generates the schema definition and its associated migration file.

$ mix phx.gen.schema Accounts.Credential credentials email:string:unique user_id:references:users
Enter fullscreen mode Exit fullscreen mode

- mix phx.gen.auth

Phoenix also provides a convenient way to generate a complete authentication system, including Ecto migrations, Phoenix context, controllers, templates, and more. This feature saves considerable time, enabling quick integration of authentication into your application.

To utilize this feature, use the mix phx.gen.auth task with the following arguments: the module name of the context, the module name of the schema, and the plural version of the schema name used for database tables and route paths.

$ mix phx.gen.auth Accounts User users
Enter fullscreen mode Exit fullscreen mode

When mix phx.gen.auth is done creating files, it helpfully tells us that we need to re-fetch our dependencies as well as run our Ecto migrations.

Please re-fetch your dependencies with the following command:

    mix deps.get

Remember to update your repository by running migrations:

  $ mix ecto.migrate

Once you are ready, visit "/users/register"
to create your account and then access to "/dev/mailbox" to
see the account confirmation email.
Enter fullscreen mode Exit fullscreen mode

- mix phx.gen.channel and mix phx.gen.socket

This task will generate a basic Phoenix channel, the socket to power the channel (if you haven't created one yet), as well as a test case for it. It takes the module name for the channel as the only argument:

$ mix phx.gen.channel Room
Enter fullscreen mode Exit fullscreen mode

If your application does not have a UserSocket yet, it will ask if you want to create one:

The default socket handler - HelloWeb.UserSocket - was not found
in its default location.

Do you want to create it? [Y/n]
Enter fullscreen mode Exit fullscreen mode

By confirming, a channel will be created, and then you need to connect the socket in your endpoint:

Add the socket handler to your `lib/hello_web/endpoint.ex`, for example:

    socket "/socket", HelloWeb.UserSocket,
      websocket: true,
      longpoll: false

For the front-end integration, you need to import the `user_socket.js`
in your `assets/js/app.js` file:

    import "./user_socket.js"
Enter fullscreen mode Exit fullscreen mode

In case a UserSocket already exists or you decide to not create one, the channel generator will tell you to add it to the Socket manually:

Add the channel to your `lib/hello_web/channels/user_socket.ex` handler, for example:

    channel "rooms:lobby", HelloWeb.RoomChannel
Enter fullscreen mode Exit fullscreen mode

- mix phx.gen.presence

This task will generate a presence tracker. The module name can be passed as an argument, Presence is used if no module name is passed.

$ mix phx.gen.presence Presence
Enter fullscreen mode Exit fullscreen mode

- mix phx.routes

This task has a single purpose, to show us all the routes defined for a given router.

If we don't specify a router for this task, it will default to the router Phoenix generated for us.

$ mix phx.routes
Enter fullscreen mode Exit fullscreen mode

- mix phx.server

This is the task we use to get our application running. It takes no arguments at all. If we pass any in, they will be silently ignored.

$ mix phx.server
Enter fullscreen mode Exit fullscreen mode

If we would like to start our application and also have an IEx session open to it, we can run the Mix task within iex like this, iex -S mix phx.server.

$ iex -S mix phx.server
Enter fullscreen mode Exit fullscreen mode

That's it for the day. In the next part, we will go through some more concepts of the Phoenix framework.

If you have any suggestions/doubts, feel free to reach out to me via one of the following methods.

LinkedIn: https://www.linkedin.com/in/rushikesh-pandit-646834100/
GitHub: https://github.com/rushikeshpandit
Portfolio: https://www.rushikeshpandit.in

Top comments (1)

Collapse
 
maratk profile image
Marat

great article! keep up the good work!