Hi everyone!
I wanted to share a new open-source package I’ve been working on to solve a common pain point when building large-scale applications with Yii2: the lack of type-safety and IDE autocompletion in model validation rules.
As we all know, the traditional way of defining rules in Yii2 relies heavily on nested arrays and magic strings:
// The traditional way (prone to typos, no IDE support)
public function rules()
{
return [
[['email'], 'required'],
[['email'], 'email'],
[['status'], 'integer', 'min' => 1, 'max' => 10],
];
}
If you misspell ‘integer’ or type ‘mn’ instead of ‘min’, the IDE won’t warn you, and you’ll only find out at runtime.
To fix this, I created yii2-fluent-rules. It provides an object-oriented, fluent builder API that brings strict typing and full autocompletion to your model rules.
How it looks:
use ovargas\fluentrules\RuleBuilder;
use ovargas\fluentrules\Attribute;
public function rules()
{
return RuleBuilder::rules([
Attribute::create('email')->notNull()->email(),
Attribute::create('status')->integer()->min(1)->max(10)
]);
}
Key Features:
-
100% Type-Safe: Every core Yii2 validator has its own dedicated builder with typed methods. -
Full IDE Autocompletion: No more guessing property names or looking up the documentation for validator configurations. -
Seamless Migration-to-Rule Mapping: The fluent API closely mirrors standard database column definitions, making it incredibly fast and intuitive to translate your database migrations into model rules. -
Hybrid Pattern Support: You don’t have to go all-in. It seamlessly integrates with traditional array-based rules, allowing you to use the fluent builder for standard validations while keeping custom or legacy rules intact. -
Strict Quality Standards: Fully compatible with PHP 8.2+ and heavily tested under PHPStan (Level 5) to ensure architectural compliance. -
Gii Integration: The package includes a built-in Gii Template for standard model generation. Additionally, it provides an automatic parsing utility (GiiHelper) intended for library extenders.
Installation
You can install it directly via Composer:
composer require ovargas/fluentrules
Links
- GitHub Repository: GitHub - ovargasdev/yii2-fluent-rules: A type-safe fluent validation interface for Yii2. · GitHub
- Packagist: ovargas/fluentrules - Packagist.org
I would love to hear your thoughts, feedback, or any suggestions for improvements!
Best regards,
Omar