Helper Functions

Helper Functions

Introduction

Masonite works on getting rid of all those mundane tasks that developers either dread writing or dread writing over and over again. Because of this, Masonite has several helper functions that allows you to quickly write the code you want to write without worrying about imports or retrieving things from the Service Container. Many things inside the Service Container are simply retrieved using several functions that Masonite sets as builtin functions.

These functions do not require any imports and are simply just available which is similiar to the print() function. These functions are all set inside the HelpersProvider Service Provider.

It may make more sense if we take a peak at this Service Provider:

class HelpersProvider(ServiceProvider):

    wsgi = False

    def register(self):
        pass

    def boot(self, View, ViewClass, Request):
        ''' Add helper functions to Masonite '''
        builtins.view = View
        builtins.request = Request.helper
        builtins.auth = Request.user
        builtins.container = self.app.helper
        builtins.env = os.getenv
        builtins.resolve = self.app.resolve

        ViewClass.share({'request': Request.helper, 'auth': Request.user})

Notice how we simply just add builtin functions via this provider.

Request

The Request class has a simple request() helper function.

is exactly the same as:

View

The view() function is just a shortcut to the View class.

is exactly the same as:

Auth

The auth() function is a shortcut around getting the current user. We can retrieve the user like so:

is exactly the same as:

This will return None if there is no user.

Container

We can get the container by using the container() function

is exactly the same as:

Env

We may need to get some environment variables inside our controller or other parts of our application. For this we can use the env() function.

is exactly the same as:

Resolve

We can resolve anything from the container by using his resolve() function.

is exactly the same as:

That's it! These are simply just functions that are added to Python's builtin functions.

Last updated