Table of Contents
Example project
Installation
The models
Determining the context
Accessing the context
That’s all folks
Home Backend Development PHP Tutorial Building a multi-tenant application with honeystone/context

Building a multi-tenant application with honeystone/context

Aug 10, 2024 pm 10:30 PM

Not to be confused with Laravel’s new context library, this package can be used to build multi-context multi-tenant applications. Most multi-tenant libraries essentially have a single ‘tenant’ context, so if you need multiple contexts, things can get a bit fiddly. This new package solves that problem.

Let’s look at an example shall we?

Example project

For our example application we’ll have a global user-base that is organised into teams and each team will have multiple projects. This is a fairly common structure in many Software as a Service applications.

It’s not uncommon for multi-tenant applications to have each user-base exist within a tenant context, but for our example application, we want users to be able to join multiple teams, so global user-base it is.
Global user-base vs tenant user-base diagram

Building a multi-tenant application with honeystone/context

As a SaaS, it’s likely that the team would be the billable entity (i.e. the seat) and certain team members would be granted permission to manage the team. I won’t dive into these implementation details in this example though, but hopefully it provides some additional context.

Installation

To keep this post concise I won’t explain how to start your Laravel project. There are many better resources available for that already, not least the official documentation. let's just assume you already have a Laravel project, with User, Team and Project models, and you’re ready to start implementing our context package.

Installation is a simple composer commend:

composer install honeystone/context
Copy after login

This library has a convenience function, context(), which as of Laravel 11 clashes with Laravel's own context function. This is not really a problem. You can either import our function:

use function Honestone\Context\context;
Copy after login

Or just use Laravel’s dependency injection container. Throughout this post I will assume you have imported the function and use it accordingly.

The models

Let’s start by configuring our Team model:

<?php declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Team extends Model
{
    protected $fillable = [&#39;name&#39;];

    public function members(): BelongsToMany
    {
        return $this->belongsToMany(User::class);
    }

    public function projects(): HasMany
    {
        return $this->hasMany(Project::class);
    }
}
Copy after login

A team has a name, members and projects. Within our application, only members of a team will be able to access the team or its projects.

Okay, so let’s look at our Project:

<?php declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Project extends Model
{
    protected $fillable = [&#39;name&#39;];

    public function team(): BelongsTo
    {
        return $this->belongsTo(Team::class);
    }
}
Copy after login

A project has a name and belongs to a team.

Determining the context

When someone accesses our application, we need to determine which team and project they are working within. To keep things simple, let’s handle this with route parameters. We’ll also assume that only authenticated users can access the application.

Neither team nor project context: app.mysaas.dev
Only team context: app.mysaas.dev/my-team
Team and project context: app.mysaas.dev/my-team/my-project

Our routes will look something like this:

Route::middleware('auth')->group(function () {

    Route::get('/', DashboardController::class);

    Route::middleware(AppContextMiddleware::Class)->group(function () {

        Route::get('/{team}', TeamController::class);
        Route::get('/{team}/{project}', ProjectController::class);
    });
});
Copy after login

This is a very inflexible approach, given the potential for namespace clashes, but it keeps the example concise. In a real world application you’ll want to handle this a little differently, perhaps anothersaas.dev/teams/my-team/projects/my-project or my-team.anothersas.dev/projects/my-project.

We should look at our AppContextMiddleware first. This middleware initialises the team context and, if set, the project context:

<?php declare(strict_types=1);

namespace App\Http\Middleware;

use function Honestone\Context\context;

class TeamContextMiddleware
{
    public function handle(Request $request, Closure $next): mixed
    {
        //pull the team parameter from the route
        $teamId = $request->route('team');
        $request->route()->forgetParameter('team');

        $projectId = null;

        //if there's a project, pull that too
        if ($request->route()->hasParamater('project')) {

            $projectId = $request->route('project');
            $request->route()->forgetParameter('project');
        }

        //initialise the context
        context()->initialize(new AppResolver($teamId, $projectId));
    }
}
Copy after login

To start with we grab the team id from the route and then forget the route parameter. We don’t need the parameter reaching our controllers once it’s in the context. If a project id is set, we pull that too. We then initialise the context using our AppResolver passing our team id and our project id (or null):

<?php declare(strict_types=1);

namespace App\Context\Resolvers;

use App\Models\Team;
use Honeystone\Context\ContextResolver;
use Honeystone\Context\Contracts\DefinesContext;

use function Honestone\Context\context;

class AppResolver extends ContextResolver
{
    public function __construct(
        private readonly int $teamId,
        private readonly ?int $projectId = null,
    ) {}

    public function define(DefinesContext $definition): void 
    {
        $definition
            ->require('team', Team::class)
            ->accept('project', Project::class);
    }

    public function resolveTeam(): ?Team
    {
        return Team::with('members')->find($this->teamId);
    }

    public function resolveProject(): ?Project
    {
        return $this->projectId ?: Project::with('team')->find($this->projectId);
    }

    public function checkTeam(DefinesContext $definition, Team $team): bool
    {
        return $team->members->find(context()->auth()->getUser()) !== null;
    }

    public function checkProject(DefinesContext $definition, ?Project $project): bool
    {
        return $project === null || $project->team->id === $this->teamId;
    }

    public function deserialize(array $data): self
    {
        return new static($data['team'], $data['project']);
    }
}
Copy after login

A little bit more going on here.

The define() method is responsible for defining the context being resolved. The team is required and must be a Team model, and the project is accepted (i.e. optional) and must be a Project model (or null).

resolveTeam() will be called internally on initialisation. It returns the Team or null. In the event of a null response, the CouldNotResolveRequiredContextException will be thrown by the ContextInitializer.

resolveProject() will also be called internally on initialisation. It returns the Project or null. In this case a null response will not result in an exception as the project is not required by the definition.

After resolving the team and project, the ContextInitializer will call the optional checkTeam() and checkProject() methods. These methods carry out integrity checks. For checkTeam() we ensure that the authenticated user is a member of the team, and for checkProject() we check that the project belongs to the team.

Finally, every resolver needs a deserialization() method. This method is used to reinstate a serialised context. Most notably this happens when the context is used in a queued job.

Now that our application context is set, we should use it.

Accessing the context

As usual, we’ll keep it simple, if a little contrived. When viewing the team we want to see a list of projects. We could build our TeamController to handle this requirements like this:

<?php declare(strict_types=1);

namespace App\Http\Controllers;

use Illuminate\View\View;

use function compact;
use function Honestone\Context\context;
use function view;

class TeamController
{
    public function __invoke(Request $request): View
    {
        $projects = context(&#39;team&#39;)->projects;

        return view('team', compact('projects'));
    }
}
Copy after login

Easy enough. The projects belonging to the current team context are passed to our view. Imagine we now need to query projects for a more specialised view. We could do this:

<?php declare(strict_types=1);

namespace App\Http\Controllers;

use Illuminate\View\View;

use function compact;
use function Honestone\Context\context;
use function view;

class ProjectQueryController
{
    public function __invoke(Request $request, string $query): View
    {
        $projects = Project::where(&#39;team_id&#39;, context(&#39;team&#39;)->id)
            ->where('name', 'like', "%$query%")
            ->get();

        return view('queried-projects', compact('projects'));
    }
}
Copy after login

It’s getting a little fiddly now, and it’s far too easy to accidentally forget to ‘scope’ the query by team. We can solve this using the BelongsToContext trait on our Project model:

<?php declare(strict_types=1);

namespace App\Models;

use Honeystone\Context\Models\Concerns\BelongsToContext;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Project extends Model
{
    use BelongsToContext;

    protected static array $context = [&#39;team&#39;];

    protected $fillable = [&#39;name&#39;];

    public function team(): BelongsTo
    {
        return $this->belongsTo(Team::class);
    }
}
Copy after login

All project queries will now be scooped by the team context and the current Team model will be automatically injected into new Project models.

Let’s simplify that controller:

<?php declare(strict_types=1);

namespace App\Http\Controllers;

use Illuminate\View\View;

use function compact;
use function view;

class ProjectQueryController
{
    public function __invoke(Request $request, string $query): View
    {
        $projects = Project::where(&#39;name&#39;, &#39;like&#39;, "%$query%")->get();

        return view('queried-projects', compact('projects'));
    }
}
Copy after login

That’s all folks

From here onwards, you’re just building your application. The context is easily at hand, your queries are scoped and queued jobs will automagically have access to the same context from which they were dispatched.

Not all context related problems are solved though. You’ll probably want to create some validation macros to give your validation rules a little context, and don’t forget manual queries will not have the context automatically applied.

If you’re planning to use this package in your next project, we’d love to hear from you. Feedback and contribution is always welcome.

You can checkout the GitHub repository for additional documentation. If you find our package useful, please drop a star.

Until next time..


This article was originally posted to the Honeystone Blog. If you like our articles, consider checking our more of our content over there.

The above is the detailed content of Building a multi-tenant application with honeystone/context. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1237
24
Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

See all articles