search
HomeBackend DevelopmentPHP TutorialBuilding a multi-tenant application with honeystone/context

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

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;

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);
    }
}

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);
    }
}

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);
    });
});

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));
    }
}

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']);
    }
}

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'));
    }
}

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'));
    }
}

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);
    }
}

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'));
    }
}

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
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
PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 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.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 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.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 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

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.