ensi-models
Ensi Models Skill
This skill helps you work with Eloquent models in Ensi projects following the project's established patterns and conventions.
Project Structure Understanding
Ensi uses Domain-Driven Design (DDD) with the following structure:
- Models:
app/Domain/{DomainName}/Models/ - Factories:
app/Domain/{DomainName}/Models/Tests/Factories/ - All models extend
Illuminate\Database\Eloquent\Model - All factories extend
Ensi\LaravelTestFactories\BaseModelFactory
Key Patterns and Conventions
Model Patterns
- PHPDoc Annotations: Use PHPDoc for all properties with Russian descriptions
- Date Types: Use
CarbonInterfacefor date fields - Type Safety: Use fully typed relationships and methods
- Factory Method: Every model should have a
factory()method - Scopes: Use scopes for complex query logic
Factory Patterns
- Base Extension: Extend
BaseModelFactoryfrom Ensi - Definition Method: Implement
definition()with faker data - State Methods: Create descriptive state methods (e.g.,
active(),inactive())
Common Properties
Standard model properties include:
$table- database table name$fillable- mass assignable fields$casts- type casting rules$attributes- default attribute values- Constants for default values (e.g.,
DEFAULT_SORT)
Workflow
When working with models in Ensi service:
1. Understand the Context
- Identify the domain (e.g., Contents, Seo, Nameplates)
- Check for existing models in the same domain
- Look at existing patterns in similar models
2. Create Models
- Follow PHPDoc patterns with Russian descriptions
- Include proper type hints
- Add relationships with return type hints
- Include factory() method
- Use appropriate casts for data types
3. Create Factories
- Extend BaseModelFactory
- Use $this->faker for test data
- Create meaningful state methods
- Handle relationships properly
4. Add Relationships
- Use proper relationship types (BelongsTo, HasMany, etc.)
- Type hint return values
- Include PHPDoc for related properties
- Follow naming conventions
5. Add Scopes
- Prefix with
scope - Accept Builder as first parameter
- Return Builder instance
- Use descriptive names
6. Create Migrations
- Follow Laravel migration patterns
- Use appropriate column types
- Include indexes and constraints
- Follow naming conventions
Code Examples
Model Example
<?php
namespace App\Domain\Contents\Models;
use App\Domain\Contents\Models\Tests\Factories\BannerFactory;
use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* @property int $id - id баннера
* @property string $name - имя
* @property bool $is_active - активность баннера
* @property CarbonInterface $created_at
* @property CarbonInterface $updated_at
*
* @property-read BannerType|null $type
*/
class Banner extends Model
{
protected $table = 'banners';
protected $fillable = [
'name',
'is_active',
];
protected $casts = [
'is_active' => 'bool',
];
public function type(): BelongsTo
{
return $this->belongsTo(BannerType::class);
}
public static function factory(): BannerFactory
{
return BannerFactory::new();
}
}
Factory Example
<?php
namespace App\Domain\Contents\Models\Tests\Factories;
use App\Domain\Contents\Models\Banner;
use Ensi\LaravelTestFactories\BaseModelFactory;
class BannerFactory extends BaseModelFactory
{
protected $model = Banner::class;
public function definition(): array
{
return [
'name' => $this->faker->words(3, true),
'is_active' => $this->faker->boolean,
];
}
public function active(): static
{
return $this->state([
'is_active' => true,
]);
}
}
Best Practices
- Consistency: Follow existing patterns in the project
- Type Safety: Always use type hints and return types
- Documentation: Include clear PHPDoc comments
- Testing: Always create factories with models
- Relationships: Use proper relationship types and foreign key conventions
- Scopes: Create reusable query logic in scopes
- Naming: Use clear, descriptive names following conventions
Common Tasks
- Create new model: Generate model with factory following domain structure
- Add relationship: Add typed relationship method with PHPDoc
- Create factory: Generate factory with meaningful state methods
- Add scope: Create scope method for common queries
- Create migration: Generate migration following Laravel conventions
- Modify existing model: Update while maintaining patterns and consistency
Always examine existing models in the same domain to maintain consistency across the codebase.
More from ensi-platform/skills
ensi-code-style
Enforce PHP and Laravel code style according to Ensi guidelines. Use this skill whenever writing, modifying, or reviewing PHP/Laravel code in Ensi projects, creating new classes (Controllers, Models, Actions, Events, etc.), refactoring existing code, setting up validation, routes, migrations, or working with Domain/Http layers in Laravel applications. Also trigger when checking code style compliance or generating Laravel components to ensure they follow Ensi conventions.
9ensi-openapi
Работайте с OpenAPI спецификациями в сервисах Ensi. Используйте этот скилл всегда, когда пользователь упоминает OpenAPI, API спецификации, создание endpoints, схем, перечислений или работу с yaml файлами в `public/api-docs/`. Также используйте при упоминании Swagger, спецификаций API, создании новых API endpoints или обновлении существующей документации API.
9ensi-api-design
Apply Ensi API Design Guide principles when designing, implementing, or reviewing REST API endpoints in Ensi projects. Use this skill when creating API endpoints, defining request/response formats, implementing filters and pagination, working with OpenAPI specifications, or any API-related work in Ensi services.
8ensi-query-builder
Создание и модификация Query классов для spatie/laravel-query-builder в Ensi сервисах. Использовать при работе с Query классами, фильтрами API, search endpoints, allowedFilters, allowedSorts, allowedIncludes, а также при упоминании фильтрации в контроллерах API, создании search-эндпоинтов, добавлении фильтров к моделям.
8ensi-meta
Создание и модификация meta эндпоинтов в Ensi сервисах. Использовать при работе с мета-информацией полей, Field классами, ModelMetaResource, EnumInfo классами, а также при упоминании meta методов в контроллерах, создании мета-эндпоинтов, настройке фильтров/сортировки для фронтенда.
7ensi-kafka
Work with Kafka in Ensi Laravel services following project standards. Use this skill whenever the user mentions creating Kafka producers, consumers, observers, or any Kafka-related work in Ensi context. This includes requests like "create a Kafka producer for Product entity", "set up Kafka consumer", "add observer to send events", "create Kafka payload", "configure Kafka topics", or any work related to Kafka integration, message producers/consumers, observers, or event-driven architecture in Ensi Laravel projects.
6