저장소가 포함된 Laravel 애플리케이션은 의미가 없습니다.

PHPz
풀어 주다: 2024-08-02 09:42:23
원래의
864명이 탐색했습니다.

Your Laravel application with Repository doesn

수년 동안 많은 개발자가 Laravel과 함께 저장소 패턴을 사용하여 애플리케이션에 깔끔한 아키텍처 개념을 적용하려고 시도했지만 종종 Laravel과 같은 프레임워크 사용에 대한 일반적인 개념을 오해하는 것을 보았습니다. .

시작하기 전에 여러분이 던질 수 있는 돌을 피해야 한다는 점을 분명히 하고 싶습니다. 이는 여러 언어, 프레임워크를 사용하고 처음부터 소프트웨어를 구축하며 작업해 온 소프트웨어 엔지니어로서 내 의견입니다. 오래된 레거시 코드베이스를 유지합니다. 내 말은 최종적이지 않으며 항상 그렇듯이 소프트웨어 엔지니어링 질문에 대한 가장 수용 가능한 대답은 "문제 해결을 위해 무엇을 교환할 것인지에 달려 있습니다."라고 생각합니다.

자, 이제 본론으로 들어가겠습니다.

클린 아키텍처란?

클린 아키텍처는 유지 관리, 테스트 및 이해가 쉬운 시스템을 만드는 것을 목표로 하는 소프트웨어 설계 철학입니다. 이는 한 부분의 변경이 다른 부분에 부정적인 영향을 미치지 않도록 시스템의 여러 부분 사이에 우려 사항을 분리하고 경계를 만드는 것을 강조합니다. 이 아키텍처는 Robert C. Martin(Bob 삼촌)에 의해 대중화되었으며 비즈니스 규칙이나 기술 요구 사항의 변화에 ​​탄력적으로 대응하는 방식으로 코드 구성을 안내하는 데 자주 사용됩니다.

간단히 말해서 Bob이 제안하는 것은 비즈니스 로직이 외부 종속성과 분리되어 이동성과 단일 책임 컨텍스트를 제공할 수 있도록 애플리케이션을 핵심 원칙을 따르는 여러 계층으로 분할해야 한다는 것입니다. 하지만 이 글은 깔끔한 아키텍처 기사가 아닐 것입니다. 나는 단지 그것에 대해 우리를 같은 입장에 두고 싶었을 뿐입니다.

Laravel과 Clean Architecture는 어떻습니까?

프레임워크에 관해서는 종속성의 긴밀한 결합에 대해 이야기하고 있습니다. 아마도 Doctrine을 사용하기 위해 Laravel을 선택하지 않았을 것입니다. 아마도 Eloquent를 사용하기 위해 선택했을 것입니다. 여러분이 찾을 수 있는 모든 프레임워크 기능에 대해서도 마찬가지입니다. 개발 속도와 편의성을 위해 프레임워크를 선택하는 것입니다.

그래서 제 질문은: 단순하다고 선택한 것에 왜 복잡성 레이어를 추가하겠습니까?

잠깐, 내가 이런 말을 한다고 해서 미워하지 마세요. Laravel을 사용하면 클린 아키텍처를 적용하거나 사용할 수도 있지만 아키텍처 결정에서 가장 중요한 측면은 달성하려는 목표와 해당 선택의 장단점을 명확하게 이해하는 것입니다.

어려운 결정이며 구현 중에 마음이 바뀔 수 있습니다. 소프트웨어는 불변이어서는 안 됩니다. 그렇죠? 소프트웨어 품질에 관한 전체 기사가 있는데 이 기사를 참조하세요.

어쨌든 Laravel로 돌아가서 아키텍처를 정리하세요. 내 생각으로는 가장 짜증나는 접근 방식 중 하나는 Eloquent에서 Repository 패턴을 사용하는 것이며, 이것이 제가 이 글을 쓰게 된 동기가 되었습니다.

저장소 패턴

리포지토리 패턴은 도메인 개체의 메모리 내 컬렉션 역할을 하며 도메인과 데이터 매핑 레이어 사이를 중재하는 디자인 패턴입니다. 도메인과 데이터 매핑 레이어를 분리하는 것을 목표로 합니다.

따라서 저장소 정의는 도메인 엔터티입니다. 왜? 이는 도메인과 상호 작용하고 인프라가 도메인과 상호 작용하는 방식을 정의하여 도메인과 애플리케이션의 인프라 계층 간의 계약 역할을 하기 때문입니다.

Laravel의 저장소 패턴

먼저 Laravel 애플리케이션에서 자주 볼 수 있는 저장소 패턴의 잘못된 구현을 보여주고 수정해 보겠습니다.

// app/Repositories/UserRepositoryInterface.php
<?php

namespace App\Repositories;

interface UserRepositoryInterface
{
  // ...methods definitions
}
로그인 후 복사
// app/Repositories/UserRepository.php
<?php

namespace App\Repositories;

class UserRepository implements UserRepositoryInterface
{
   // ...implementation
}
로그인 후 복사

위 코드에서 볼 수 있듯이 도메인과 인프라와의 '계약'은 도메인 내부가 아니라 인프라 자체 내부에서 정의됩니다. 예, 앱 네임스페이스는 애플리케이션 계층의 일부이며 도메인이 아닌 모든 항목을 포함합니다.

이제 동일한 것을 어떻게 구현하는지 살펴보겠습니다.

// domain/Repositories/UserRepositoryInterface.php
<?php

namespace Domain\Repositories;

interface UserRepositoryInterface
{
  // ...methods definitions
}
로그인 후 복사
// app/Repositories/UserRepository.php
<?php

namespace App\Repositories;

use Domain\Repositories\UserRepositoryInterface;

class UserRepository implements UserRepositoryInterface
{
   // ...implementation
}
로그인 후 복사

이제 적절한 도메인 레이어와 애플리케이션 레이어가 생겼습니다. 구하기가 꽤 간단하죠?

Eloquent를 사용한 리포지토리 패턴

이제 좀 생각해 보겠습니다. 리포지토리 인터페이스가 이제 도메인의 일부이므로 다른 레이어의 종속성을 도메인에 간단히 주입할 수는 없습니다. 이를 설명하는 나쁜 예는 다음과 같습니다.

// app/Repositories/UserRepositoryInterface.php
<?php

namespace App\Repositories;

use App\Models\User;

interface UserRepositoryInterface
{
  public function find(int $id): User|null;
  // ...other methods
}
로그인 후 복사

아직 확실하지 않나요? 도메인 레이어로 이동하겠습니다:

// domain/Repositories/UserRepositoryInterface.php
<?php

namespace Domain\Repositories;

use App\Models\User;

interface UserRepositoryInterface
{
  public function find(int $id): User|null;
  // ...other methods
}
로그인 후 복사

문제가 보이나요? 우리는 인프라 계층의 일부인 Eloquent 모델을 우리 도메인에 주입하고 있습니다. 이는 우리 도메인을 Eloquent와 긴밀하게 연결하여 리포지토리 패턴의 목적을 무너뜨립니다.

But how do we solve it? Well, it is not as hard as you might think. You probably already heard about Entities, right? So, let’s fix it:

// domain/Repositories/UserRepositoryInterface.php
<?php

namespace Domain\Repositories;

use Domain\Entities\User;

interface UserRepositoryInterface
{
  public function find(int $id): User|null;
  // ...other methods
}
로그인 후 복사
// domain/Entities/User.php
<?php

namespace Domain\Entities;

class User
{
  public function __construct(
    public int $id;
    public string $name;
    public string $email;
  ) {}
  // ...other properties and methods
}
로그인 후 복사

Our domain layer is now clean from external dependencies, and if we want to move the whole domain to another framework, we can do it.

Now, how do we implement our Repository in our Laravel application? Let me show you:

// app/Repositories/EloquentUserRepository.php
<?php

namespace App\Repositories;

use Domain\Repositories\UserRepositoryInterface;
use Domain\Entities\User;
use App\Models\User as EloquentUser;

class EloquentUserRepository implements UserRepositoryInterface
{
    public function find(int $id): ?User {
        $eloquentUser = EloquentUser::find($id);
        return $eloquentUser ? $this->toDomain($eloquentUser): null;
    }

    private function toDomain(EloquentUser $eloquentUser): User
    {
        return new User(
          $eloquentUser->id, 
          $eloquentUser->name, 
          $eloquentUser->email
        );
    }
}
로그인 후 복사

Now we have a proper implementation of the Repository pattern in Laravel using Eloquent. You can create any other Repository implementation, such as PDOUserRepository.php, DoctrineUserRepository.php, and many others without injecting any dependency into your Domain layer.

Do You Really Need to Use Repository?

Back to what I said in the subject of this article, I’ll complement that, in my humble opinion, using the Repository Pattern with Laravel is just overengineering, and you need a really good reason to do it.

You are adding an extra layer of complexity to your application that you may not need at all, or even worse, it will not guarantee that your business logic is actually isolated into the Domain layer.

What are you trying to achieve here? Think about it. You might end up missing out on many nice functionalities from Laravel or at least making their usage overly complicated.

Are you not sure if Laravel is the best framework for your application and you might move your application to Symfony in the future? Sure, go for the Domain and the Repository. Do you need to replace your SQL database with a NoSQL database later? Maybe it is a good justification. But do you really need it, or is it just charm?

One common argument is that the Repository helps to put some business logic into a separate layer. This normally gives me the creeps because there are better approaches for splitting your logic. Repositories are just for acting as a middle layer to connect the data layer and domain, nothing else. If you want to split your business logic, you should make use of something else — but this is another subject.

Conclusion

In conclusion, while the Repository pattern and clean architecture principles offer significant benefits in terms of maintainability and separation of concerns, their application in a Laravel context often introduces unnecessary complexity. Laravel is designed for simplicity and rapid development, and adding layers of abstraction can complicate this process.

Before implementing the Repository pattern, it is essential to evaluate your project’s specific needs. If decoupling your domain logic from Laravel’s infrastructure is a genuine necessity due to future migrations or a need for flexibility, then the complexity might be warranted. However, for many Laravel applications, leveraging Eloquent directly aligns better with the framework’s strengths and keeps the codebase simpler and more maintainable.

Ultimately, the decision should be driven by a clear understanding of your project’s requirements, balancing the trade-offs involved. Overengineering can lead to more problems than it solves, so aim to keep your solutions as straightforward as possible while still achieving your design goals. The primary objective of any architecture is to solve problems, not to create new ones.

위 내용은 저장소가 포함된 Laravel 애플리케이션은 의미가 없습니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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