허니스톤/컨텍스트를 사용하여 다중 테넌트 애플리케이션 구축

PHPz
풀어 주다: 2024-08-12 15:11:25
원래의
911명이 탐색했습니다.

Laravel의 새로운 컨텍스트 라이브러리와 혼동하지 마세요. 이 패키지는 다중 컨텍스트 다중 테넌트 애플리케이션을 구축하는 데 사용할 수 있습니다. 대부분의 다중 테넌트 라이브러리에는 기본적으로 단일 '테넌트' 컨텍스트가 있으므로 여러 컨텍스트가 필요한 경우 상황이 약간 까다로워질 수 있습니다. 이 새로운 패키지는 그 문제를 해결합니다.

예제를 살펴볼까요?

예시 프로젝트

예제 애플리케이션의 경우 팀으로 구성된 글로벌 사용자 기반이 있고 각 팀에는 여러 프로젝트가 있습니다. 이는 많은 SaaS(Software as a Service) 애플리케이션에서 상당히 일반적인 구조입니다.

다중 테넌트 애플리케이션에서 각 사용자 기반이 테넌트 컨텍스트 내에 존재하는 것은 드문 일이 아니지만, 예제 애플리케이션에서는 사용자가 여러 팀에 참여할 수 있기를 원하므로 글로벌 사용자 기반입니다.
글로벌 사용자 기반과 테넌트 사용자 기반 다이어그램

Building a multi-tenant application with honeystone/context

SaaS에서는 팀이 청구 가능 개체(예: 좌석)가 되고 특정 팀 구성원에게 팀을 관리할 수 있는 권한이 부여될 가능성이 높습니다. 이 예에서는 이러한 구현 세부 사항을 자세히 다루지는 않지만 추가 컨텍스트를 제공할 수 있기를 바랍니다.

설치

이 게시물을 간결하게 유지하기 위해 Laravel 프로젝트를 시작하는 방법에 대해서는 설명하지 않겠습니다. 공식 문서뿐만 아니라 이미 이를 위한 더 나은 리소스가 많이 있습니다. 사용자, 팀 및 프로젝트 모델이 포함된 Laravel 프로젝트가 이미 있고 컨텍스트 패키지 구현을 시작할 준비가 되었다고 가정해 보겠습니다.

설치는 간단한 작곡가 추천입니다:

으아악

이 라이브러리에는 Laravel 11부터 Laravel 자체 컨텍스트 기능과 충돌하는 편리한 함수인 context()가 있습니다. 이것은 실제로 문제가 되지 않습니다. 우리의 기능을 가져올 수 있습니다:

으아악

또는 Laravel의 종속성 주입 컨테이너를 사용하세요. 이 게시물 전체에서 나는 당신이 함수를 가져왔고 그에 따라 사용한다고 가정할 것입니다.

모델

팀 모델 구성부터 시작해 보겠습니다.

으아악

팀에는 이름, 구성원, 프로젝트가 있습니다. 우리 애플리케이션 내에서는 팀 구성원만 팀이나 해당 프로젝트에 액세스할 수 있습니다.

좋아, 그럼 우리 프로젝트를 살펴보자:

으아악

프로젝트에는 이름이 있고 팀에 속합니다.

컨텍스트 결정

누군가 우리 애플리케이션에 액세스하면 그 사람이 어떤 팀과 프로젝트에서 작업하고 있는지 확인해야 합니다. 작업을 단순하게 유지하기 위해 경로 매개변수를 사용하여 이를 처리하겠습니다. 또한 인증된 사용자만 애플리케이션에 액세스할 수 있다고 가정하겠습니다.

팀이나 프로젝트 컨텍스트 모두: app.mysaas.dev
팀 컨텍스트만: app.mysaas.dev/my-team
팀 및 프로젝트 컨텍스트: app.mysaas.dev/my-team/my-project

우리의 경로는 다음과 같습니다:

으아악

이것은 네임스페이스 충돌 가능성을 고려할 때 매우 경직된 접근 방식이지만 예제를 간결하게 유지합니다. 실제 애플리케이션에서는 이를 약간 다르게 처리하고 싶을 것입니다. 아마도 anothersaas.dev/teams/my-team/projects/my-project 또는 my-team.anothersas.dev/projects/my-project가 될 것입니다.

먼저 AppContextMiddleware를 살펴봐야 합니다. 이 미들웨어는 팀 컨텍스트를 초기화하고, 설정된 경우 프로젝트 컨텍스트를 초기화합니다.

으아악

우선 경로에서 팀 ID를 가져온 다음 경로 매개변수를 잊어버립니다. 매개변수가 컨텍스트에 있으면 컨트롤러에 도달하는 매개변수가 필요하지 않습니다. 프로젝트 ID가 설정되어 있으면 해당 ID도 가져옵니다. 그런 다음 팀 ID와 프로젝트 ID(또는 null)를 전달하는 AppResolver를 사용하여 컨텍스트를 초기화합니다.

으아악

여기서 조금 더 진행됩니다.

define() 메서드는 해결되는 컨텍스트를 정의하는 역할을 합니다. 팀은 필수이며 팀 모델이어야 하며 프로젝트가 허용되고(즉, 선택 사항) 프로젝트 모델(또는 null)이어야 합니다.

resolveTeam()은 초기화 시 내부적으로 호출됩니다. 팀 또는 null을 반환합니다. null 응답이 발생하는 경우 ContextInitializer에 의해 CouldNotResolveRequiredContextException이 발생합니다.

resolveProject()도 초기화 시 내부적으로 호출됩니다. 프로젝트 또는 null을 반환합니다. 이 경우 정의에 따라 프로젝트가 필요하지 않으므로 null 응답으로 인해 예외가 발생하지 않습니다.

팀과 프로젝트를 해결한 후 ContextInitializer는 선택적 checkTeam() 및 checkProject() 메서드를 호출합니다. 이러한 방법은 무결성 검사를 수행합니다. checkTeam()의 경우 인증된 사용자가 팀의 구성원인지 확인하고 checkProject()의 경우 프로젝트가 팀에 속하는지 확인합니다.

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.

위 내용은 허니스톤/컨텍스트를 사용하여 다중 테넌트 애플리케이션 구축의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!