>  기사  >  백엔드 개발  >  DTO(데이터 전송 객체)의 장점과 PHP 읽기 전용 클래스가 Laravel 코드를 향상시키는 방법을 살펴보세요.

DTO(데이터 전송 객체)의 장점과 PHP 읽기 전용 클래스가 Laravel 코드를 향상시키는 방법을 살펴보세요.

PHPz
PHPz원래의
2024-07-30 08:59:091159검색

Explore the Advantages of Data Transfer Objects (DTOs) and How PHP  Readonly Classes Can Elevate Your Laravel Code

현대 웹 애플리케이션 개발에서는 데이터를 효율적이고 안전하게 관리하고 전송하는 것이 중요합니다. 이 프로세스에 크게 도움이 되는 디자인 패턴 중 하나는 DTO(데이터 전송 개체)입니다. 이 게시물에서는 특히 Laravel 애플리케이션에서 DTO를 사용할 때의 이점을 살펴보고 PHP 8.2 읽기 전용 클래스가 그 이점을 더욱 향상시킬 수 있는 방법을 보여줍니다.

데이터 전송 개체(DTO)란 무엇입니까?

DTO(데이터 전송 개체)는 프로세스나 시스템 간에 데이터를 전달하도록 설계된 간단한 개체입니다. 일반적인 모델이나 엔터티와 달리 DTO에는 비즈니스 논리가 없습니다. 이는 데이터를 캡슐화하여 애플리케이션의 서로 다른 계층 간에 또는 다양한 시스템 간에 정보를 전송하는 명확하고 구조화된 방법을 제공합니다.

DTO 패턴

DTO 패턴은 소프트웨어 애플리케이션 내의 다양한 하위 시스템에 데이터를 전송하는 데 사용됩니다. DTO 사용의 주요 목적은 메서드 호출 수를 최소화하고, 필요한 데이터를 집계하며, 데이터 변환 및 유효성 검사를 관리하기 위한 구조화된 접근 방식을 제공하는 것입니다.

DTO 사용의 이점

  • 우려사항 분리: DTO는 비즈니스 로직을 데이터 표현과 분리하여 더 명확하고 유지 관리가 용이하며 이해하기 쉬운 코드를 만듭니다.

  • 데이터 유효성 검사: DTO를 사용하면 다른 애플리케이션 계층에서 데이터를 처리하기 전에 데이터 유효성을 검사하여 유효한 데이터만 사용되도록 할 수 있습니다.

  • 일관성: 데이터 전송을 위한 일관된 구조를 제공함으로써 DTO는 다양한 소스의 데이터 관리 및 처리를 단순화합니다.

  • 보안: DTO는 어떤 데이터에 액세스하고 수정할 수 있는지 제어하여 무단 데이터 조작으로부터 애플리케이션을 보호할 수 있습니다.

  • 테스트: DTO는 포함된 비즈니스 로직이 없는 간단한 개체이므로 모의 및 테스트가 더 간단합니다.

  • 변환: DTO는 데이터를 다양한 애플리케이션 계층에서 요구하는 형식으로 쉽게 변환합니다.

  • 불변성: DTO는 불변성을 장려하는 경우가 많습니다. 즉, 일단 생성되면 상태가 변경될 수 없다는 의미입니다. 이 기능은 다음과 같은 몇 가지 장점을 제공합니다.

    • 예측 가능성: 불변 객체는 생성 후에도 상태가 일정하게 유지되므로 예측 가능하고 추론하기가 더 쉽습니다.
    • 스레드 안전성: 불변성은 본질적으로 스레드 안전성을 지원하여 동시 처리를 단순화합니다.
    • 디버깅: 불변 객체의 상태는 수명 주기 동안 변경되지 않고 유지되므로 디버깅이 더 쉽습니다.

PHP 8.2 및 읽기 전용 클래스

PHP 8.2에서는 읽기 전용 클래스가 도입되어 DTO 사용이 향상되었습니다. 읽기 전용 클래스를 사용하면 속성을 읽기 전용으로 명시적으로 정의할 필요가 없으므로 DTO 구현이 단순화됩니다. PHP 8.2의 읽기 전용 클래스가 DTO를 개선하는 방법은 다음과 같습니다.

  • 단순화된 코드: 읽기 전용 클래스는 자동으로 속성을 불변으로 만들어 상용구 코드를 줄이고 명확성을 높입니다.
  • 강화된 보안: 읽기 전용 클래스는 한 번 설정된 속성을 수정할 수 없도록 하여 데이터 무결성과 보안을 강화합니다.
  • 향상된 유지 관리성: 데이터 불변성이 언어 자체에 의해 적용되므로 읽기 전용 클래스를 사용하면 코드가 더욱 깔끔하고 유지 관리 가능해집니다.

예: 자산 관리 시스템에서 DTO 사용

API, CSV 가져오기 등 다양한 소스에서 속성을 가져올 수 있는 속성 관리 시스템을 고려해 보겠습니다. DTO를 사용하여 속성 모델, 구독, 자산 등을 생성하여 애플리케이션 전체에서 데이터의 일관성과 유효성을 확인할 수 있습니다.

PropertyDTO 정의

먼저 PropertyDTO 클래스를 정의해 보겠습니다.

app/DTO/PropertyDTO.php

namespace App\DTO;

/**
 * Class PropertyDTO
 *
 * Represents a Data Transfer Object for property data.
 */
readonly class PropertyDTO extends AbstractDTO
{
    /**
     * The name of the property.
     *
     * @var string
     */
    public string $name;

    /**
     * The address of the property.
     *
     * @var string
     */
    public string $address;

    /**
     * The price of the property.
     *
     * @var float
     */
    public float $price;

    /**
     * The subscription status of the property, if applicable.
     *
     * @var string|null
     */
    public ?string $subscription;

    /**
     * The list of assets associated with the property.
     *
     * @var array|null
     */
    public ?array $assets;

    /**
     * Set the properties from a model instance.
     *
     * @param $model The model instance.
     * @return $this
     */
    public function setFromModel($model): self
    {
        $this->name = $model->name;
        $this->address = $model->address;
        $this->price = $model->price;
        $this->subscription = $model->subscription;
        $this->assets = $model->assets;

        return $this;
    }

    /**
     * Set the properties from API data.
     *
     * @param array $data The API data.
     * @return $this
     */
    public function setFromAPI(array $data): self
    {
        $this->name = $data['property_name'];
        $this->address = $data['property_address'];
        $this->price = $data['property_price'];
        $this->subscription = $data['subscription'] ?? null;
        $this->assets = $data['assets'] ?? null;

        return $this;
    }

    /**
     * Set the properties from CSV data.
     *
     * @param array $data The CSV data.
     * @return $this
     */
    public function setFromCSV(array $data): self
    {
        $this->name = $data[0];
        $this->address = $data[1];
        $this->price = (float) $data[2];
        $this->subscription = $data[3] ?? null;
        $this->assets = explode(',', $data[4] ?? '');

        return $this;
    }
}
PropertyDTO 사용

PropertyDTO를 사용하여 다양한 소스의 속성을 처리하는 방법은 다음과 같습니다.

// From a Model
$model = Property::find(1);
$propertyDTO = (new PropertyDTO([]))->setFromModel($model);

// From an API
$apiData = [
    'property_name' => 'Beautiful House',
    'property_address' => '1234 Elm Street',
    'property_price' => 450000,
    'subscription' => 'Premium',
    'assets' => ['pool', 'garden']
];
$propertyDTO = (new PropertyDTO([]))->setFromAPI($apiData);

// From a CSV
$csvData = ['Beautiful House', '1234 Elm Street', 450000, 'Premium', 'pool,garden'];
$propertyDTO = (new PropertyDTO([]))->setFromCSV($csvData);

// Convert to Array
$arrayData = $propertyDTO->toArray();

// Convert to JSON
$jsonData = $propertyDTO->toJson();

요약

DTO(데이터 전송 개체)는 데이터 일관성, 검증 및 문제 분리를 보장함으로써 Laravel 애플리케이션에 수많은 이점을 제공합니다. DTO를 구현하면 애플리케이션을 더욱 유지 관리하기 쉽고 안전하며 테스트하기 쉽게 만들 수 있습니다. 자산 관리 시스템에서 DTO는 API 및 CSV 가져오기와 같은 다양한 소스의 데이터를 효율적으로 처리하는 데 도움을 주어 비즈니스 로직을 깔끔하게 유지하고 검증된 데이터 처리에 집중하도록 합니다.

Moreover, embracing immutability within DTOs enhances predictability, thread-safety, and simplifies debugging.

Extending DTOs with Abstract Classes for Consistency

To streamline the creation of DTOs and promote code reuse, we can use an abstract class or base class. This approach allows us to define common methods and properties in the abstract class and extend it for specific data sources.

Defining the AbstractDTO

app/DTO/AbstractDTO.php

namespace App\DTO;

/**
 * AbstractDTO
 *
 * An abstract base class for Data Transfer Objects (DTOs).
 * Provides common methods and properties for DTO implementations.
 */
abstract class AbstractDTO
{
    /**
     * AbstractDTO constructor.
     *
     * Initialises the DTO with data from an associative array.
     *
     * @param array $data The data array to initialize the DTO.
     */
    public function __construct(array $data)
    {
        $this->setFromArray($data);
    }

    /**
     * Set the properties of the DTO from a model instance.
     *
     * @param $model The model instance from which to populate the DTO.
     * @return $this
     */
    abstract public function setFromModel($model): self;

    /**
     * Set the properties of the DTO from API data.
     *
     * @param array $data The data array from the API.
     * @return $this
     */
    abstract public function setFromAPI(array $data): self;

    /**
     * Set the properties of the DTO from CSV data.
     *
     * @param array $data The data array from the CSV.
     * @return $this
     */
    abstract public function setFromCSV(array $data): self;

    /**
     * Convert the DTO to an associative array.
     *
     * @return array The DTO data as an associative array.
     */
    public function toArray(): array
    {
        $properties = get_object_vars($this);
        return array_filter($properties, function ($property) {
            return $property !== null;
        });
    }

    /**
     * Convert the DTO to a JSON string.
     *
     * @return string The DTO data as a JSON string.
     */
    public function toJson(): string
    {
        return json_encode($this->toArray());
    }

    /**
     * Set the properties of the DTO from an associative array.
     *
     * @param array $data The data array to populate the DTO.
     */
    protected function setFromArray(array $data): void
    {
        foreach ($data as $key => $value) {
            if (property_exists($this, $key)) {
                $this->$key = $value;
            }
        }
    }
}

Final Thoughts

Using an abstract or base class for DTOs not only ensures consistency across different DTO implementations but also promotes code reuse and maintainability. By defining common methods and properties in an abstract class, you can create a structured and efficient way to manage data transfer within your application. This approach aligns well with the principles of clean code and helps in building scalable and robust applications.

Here’s a revised phrase that includes a call to action:

"By leveraging DTOs and abstract classes together, you can refine your Laravel application's design, improving how data is managed and ensuring a more organised and efficient data flow. If you want to further encapsulate and enhance your DTOs with traits and interfaces, explore our guide on Enhancing Object-Oriented Design with Traits, Interfaces, and Abstract Classes."

위 내용은 DTO(데이터 전송 객체)의 장점과 PHP 읽기 전용 클래스가 Laravel 코드를 향상시키는 방법을 살펴보세요.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.