fourfortymedia/eloquent-model-guard 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

fourfortymedia/eloquent-model-guard

Composer 安装命令:

composer require fourfortymedia/eloquent-model-guard

包简介

README 文档

README

Welcome to the readme for the eloquent-model-guard Laravel package. This package brings an array of enhancements to data validation for Eloquent models, providing developers with improved control over data integrity and validation rules. Let's dive into the details of this package.

Attributes

The eloquent-model-guard package introduces the ability to add structured and machine-readable metadata information to declarations. This enhances the control over data validation, particularly within Eloquent models, and allows for finer customization of validation rules based on specific scenarios.

Background

Database fields are characterized by types that define the nature of data they can store. These types ensure data integrity and consistency by enforcing validation rules. Typically, these setups are performed within migrations. Different data types represent various kinds of data such as numbers, strings, and dates. By indicating the type of a field, the database can validate and enforce rules to ensure only valid data is stored. This not only prevents errors but also enhances query performance and data accuracy.

While migrations establish data integrity upon storage, they are executed only once. The eloquent-model-guard package empowers users to update and adapt validation rules within the model. This offers a significant advantage in responding to changing application requirements. Developers can now effortlessly customize validation rules based on evolving business needs without altering the database structure. This dynamic and agile approach enhances the efficiency and adaptability of validation, resulting in a more robust and responsive application.

Added Features

The eloquent-model-guard package comes with several notable additions:

  • Custom Validation Rules: Developers can define validation rules using custom attributes: OnCreateRules and OnUpdateRules. This customization allows fine-tuning of validation rules based on specific scenarios.
  • validateUsing Method: The Model class now includes a validateUsing method, supporting the use of custom validation rules.
  • protected array $rules; Property: A new property has been added to conveniently store validation rules.

Changes

The following changes have been made to improve validation in Eloquent models:

  • The booted method within the Model class now automatically triggers validation during creation and updating.
  • A new static call method validateUsing has been introduced within the __callStatic method. This method can be used dynamically and statically.

Context

The enhancements brought by the eloquent-model-guard package greatly enhance data validation for Eloquent models. The introduction of OnCreateRules and OnUpdateRules attributes allows developers to craft specific validation rules for model creation and updates, respectively. This granularity in validation empowers developers to fine-tune validation for individual models, properties, or attributes, promoting cleaner code organization and more efficient validation logic.

Installation

 composer require fourfortymedia/eloquent-model-guard

In your eloquent model, add the following

class User extends Model {
     use \FourFortyMedia\EloquentModelGuard\Concerns\HasEloquentModelGuard;
}

Examples

Let's explore some usage examples to demonstrate how to take advantage of the new attributes:

  1. Validation on Creation:

    use Illuminate\Database\Eloquent\Validations\OnCreateRules;
    
    #[OnCreateRules(['name' => 'required', 'email' => 'required|email'])]
    class User extends Model {
        #[OnCreateRules(['roles.*' => 'rule1|rule2')]
        private array $roles = [];
    }
  2. Validation on Update:

    use Illuminate\Database\Eloquent\Validations\OnUpdateRules;
    
    #[OnUpdateRules(['email' => 'required|email'])]
    class User extends Model {
        // ...
    }
  3. Combining Both Attributes:

    use Illuminate\Database\Eloquent\Validations\OnUpdateRules;
    
    #[OnUpdateRules(['email' => 'required|email'])]
    #[OnCreateRules(['name' => 'required', 'email' => 'required|email'])]
    class User extends Model {
        // ...
    }
  4. Using on Model Fields: Note: When using this on the model attributes, use either private or protected on those attributes so that they don't interfere with your attributes

    use Illuminate\Database\Eloquent\Validations\OnUpdateRules;
    
    #[OnUpdateRules(['email' => 'required|email'])]
    #[OnCreateRules(['name' => 'required', 'email' => 'required|email'])]
    class User extends Model {
        #[OnUpdateRules(['required'])]
        protected string $name;
        
        #[OnUpdateRules(['email' => 'required|email'])]
        #[OnCreateRules('required|email')]
        protected string $email;
    }
    please note that when using it on a sigle property, you may pass and accosiative array with a key that is
    

    the same as the property with the value as the rules or pass rules as array or keys

  5. Custom Rules with Validation:

    $product = Product::validateUsing(function ($rules) {
        $rules['price'] = 'numeric|min:0';
        return $rules;
    })->create($data);
  6. Automatic Validation on Creation and Updating:

    protected static function booted()
    {
        static::creating(function (self $model) {
            $model->getModelRules(useOnCreateRules: false);
            $model->getPropertyRules(useOnCreateRules: false);
            $model->validate();
        });
        static::updating(function (self $model) {
            $model->getModelRules();
            $model->getPropertyRules();
            $model->validate();
        });
    }

Note

Please note that this pull request is a work in progress and is being submitted for initial review and feedback. Further improvements and adjustments will be made based on the feedback received.

Remember that the package's features only take effect when the attributes are applied to the model or properties. This package does not enforce any developer to use it, offering flexibility while providing powerful validation capabilities.

For any inquiries or feedback, feel free to contact Mr. Rikhotso, the creator of this package. Your thoughts and suggestions are highly valued.

fourfortymedia/eloquent-model-guard 适用场景与选型建议

fourfortymedia/eloquent-model-guard 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 35 次下载、GitHub Stars 达 1, 最近一次更新时间为 2023 年 08 月 11 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 fourfortymedia/eloquent-model-guard 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 fourfortymedia/eloquent-model-guard 我们能提供哪些服务?
定制开发 / 二次开发

基于 fourfortymedia/eloquent-model-guard 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: Unknown
  • 更新时间: 2023-08-11