承接 kontoulis/laravel-attribute-model-casting 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

kontoulis/laravel-attribute-model-casting

最新稳定版本:1.0.0

Composer 安装命令:

composer require kontoulis/laravel-attribute-model-casting

包简介

A Laravel package enabling the use of native PHP attributes for defining and managing Eloquent model attribute casts.

README 文档

README

Laravel 11+ Packagist Downloads License

Table of Contents

Introduction

This package introduces a Cast attribute to enhance type casting for Eloquent model attributes. By leveraging PHP 8 attributes, this package allows you to define casts in a more modern, reusable, and maintainable way, especially when working with traits.

Note: This approach can be used together with the existing Eloquent casting system. The Cast attribute will be applied in addition to any other casts defined in the model.

Motivation

Defining casts in Eloquent models can become repetitive, especially when the same casts are applied across multiple models. This package provides a clean and modern solution by allowing you to define casts using attributes, making it easier to reuse and maintain your code.

Installation

You can install the package via Composer:

composer require kontoulis/laravel-attribute-model-casting

Prerequisites

  • PHP 8.0 or higher
  • Laravel 11 or higher

Usage

Defining Casts with Attributes

You can use the Cast attribute to define type casting for model properties.
To resolve the actual casts, the model must use the included AttributeCasting trait.

Here's an example:

use Kontoulis\LaravelAttributeModelCasting\AttributeCasting;
use Kontoulis\LaravelAttributeModelCasting\Cast;

#[Cast('price', Price::class)]
trait HasPrice {
    public function priceEquals(Price $other): bool
    {
        return $this->amount === $other->amount && $this->currency === $other->currency;
    }
}

#[Cast('normalModelAttribute', 'int')]
class EloquentModelWithAttributeCasts extends Model
{
    use AttributeCasting;
    use HasPrice;
}

In this example:

  • The HasPrice trait defines a Cast attribute for the price property, allowing it to be reused across multiple models.
  • The EloquentModelWithAttributeCasts class uses the Cast attribute to define a cast for the normalModelAttribute property.

Benefits

  • Reusability: Define casts once in a trait and reuse them across multiple models.
  • Modern Syntax: Leverage PHP 8 attributes for a cleaner and more expressive syntax.
  • Reduced Redundancy: No need to manually define the same casts in every model.

Contributing

Contributions are welcome! Please open an issue or submit a pull request for any improvements or bug fixes.

License

This package is open-sourced software licensed under the MIT license.

统计信息

  • 总下载量: 2
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-06-20