v3.0
Official Packages
Masonite Essentials
Powered By GitBook
Extending Classes

Introduction

It's common to want to use a Service Provider to add new methods to a class. For example, you may want to add a is_authenticated method to the Request class. Your package and Service Provider may be for a better authentication system.
You may easily extend classes that inherit from the Extendable class. Many of the built in classes inherit from it.

Usage

You have a few options for adding methods to any of the core classes. You can extend a class with functions, classes and class methods. Typical usage may look like:
1
def is_authenticated(self):
2
return self
3
4
def show(self, request: Request):
5
6
request.extend(is_authenticated)
7
8
print(request.is_authenticated()) # returns the Request class
Copied!
Usage is very simple and has several options for extending a class. Notice that we don't call the function but we pass the reference to it.

Extending a function

This will simply add the function as a bound method to the Request class
1
def is_authenticated(self):
2
return self
3
4
def show(self, request: Request):
5
6
request.extend(is_authenticated)
7
8
print(request.is_authenticated()) # returns the Request class
Copied!

Extending a class method

We can also extend a class method which will take the method given and add it as a bound method.
1
class Authentication:
2
3
def is_authenticated(self):
4
return self
5
6
def show(self, request: Request):
7
8
request.extend(Authentication.is_authenticated)
9
10
print(request.is_authenticated()) # returns the Request class
Copied!

Extending a class

We can even extend a whole class which will get all the classes methods and create bound methods to the Request class.
1
class Authentication:
2
3
def is_authenticated(self):
4
return self
5
6
def login(self):
7
return self
8
9
def show(self, request: Request):
10
11
request.extend(Authentication)
12
13
print(request.is_authenticated()) # returns the Request class
14
print(request.login()) # returns the Request class
Copied!
Last modified 3yr ago