Code organization

From VilnaCRM-Org/user-service · View interactive version

Code organization is an AI agent skill from the GitHub repository VilnaCRM-Org/user-service. Enforce code organization principles - "Directory X contains ONLY class type X", DDD naming patterns, PHP best practices, type safety, SOLID principles, and hardcoded config extraction to .env. Use when reviewing code structure, placing classes, refactoring, fixing CI failures related to structure,

How to use this skill

Skill file

Code Organization Skill

Core Principle

Directory X contains ONLY class type X

This is the fundamental rule for code organization in this codebase.

Context (Input)

Task (Function)

Enforce strict code organization principles: proper directory structure, DDD naming conventions, specific variable names, type safety, SOLID principles, and PHP best practices.

Directory Type Classification

Classes MUST be in directories matching their type:

| Directory | Contains ONLY | Example |

| ------------------ | ------------------------------- | ---------------------------------- |

| Converter/ | Type converters | UlidTypeConverter |

| Transformer/ | Data transformers (DB/serial) | CustomerToArrayTransformer |

| Validator/ | Validation logic | UlidValidator |

| Builder/ | Object builders | QueryBuilder |

| Fixer/ | Data fixers/modifiers | DataFixer |

| Factory/ | Object factories | CustomerFactory |

| Resolver/ | Value resolvers | CustomerUpdateScalarResolver |

| Serializer/ | Serializers/normalizers | CustomerNormalizer |

| Formatter/ | Data formatters | CustomerNameFormatter |

| Mapper/ | Data mappers | PathsMapper |

| Provider/ | Data/service providers | TimestampProvider |

| Processor/ | API Platform processors | CreateCustomerProcessor |

| EventListener/ | Event listeners (Symfony) | QueryParameterValidationListener |

| EventSubscriber/ | Event subscribers (Symfony/App) | SendEmailOnCustomerCreated |

Directory Creation Guardrails

DDD Naming Patterns

By Layer and Type

| Layer | Class Type | Naming Pattern | Example |

| ------------------ | ------------------ | ------------------------------------ | --------------------------------- |

| Domain | Entity | {EntityName}.php | Customer.php |

| | Value Object | {ConceptName}.php | Email.php, Money.php |

| | Domain Event | {Entity}{PastTenseAction}.php | CustomerCreated.php |

| | Repository Iface | {Entity}RepositoryInterface.php | CustomerRepositoryInterface.php |

| | Exception | {SpecificError}Exception.php | InvalidEmailException.php |

| Application | Command | {Action}{Entity}Command.php | CreateCustomerCommand.php |

| | Command Handler | {Action}{Entity}Handler.php | CreateCustomerHandler.php |

| | Event Subscriber | {Action}On{Event}.php | SendEmailOnCustomerCreated.php |

| | DTO | {Entity}{Type}.php | CustomerInput.php |

| | Processor | {Action}{Entity}Processor.php | CreateCustomerProcessor.php |

| | Transformer | {From}To{To}Transformer.php | CustomerToArrayTransformer.php |

| Infrastructure | Repository | {Technology}{Entity}Repository.php | MySQLCustomerRepository.php |

| | Doctrine Type | {ConceptName}Type.php | UlidType.php |

| | Bus Implementation | {Framework}{Type}Bus.php | SymfonyCommandBus.php |

Directory Structure by Layer

src/{Context}/
├── Application/
│   ├── Command/          ← Commands
│   ├── CommandHandler/   ← Command Handlers
│   ├── EventSubscriber/  ← Event Subscribers
│   ├── DTO/              ← Data Transfer Objects
│   ├── Processor/        ← API Platform Processors
│   ├── Transformer/      ← Data Transformers
│   ├── Validator/        ← Validators
│   ├── Converter/        ← Type Converters
│   ├── Resolver/         ← Value Resolvers
│   ├── Factory/          ← Factories
│   ├── Builder/          ← Builders
│   ├── Formatter/        ← Formatters
│   └── MutationInput/    ← GraphQL Mutation Inputs
├── Domain/
│   ├── Entity/           ← Entities & Aggregates
│   ├── ValueObject/      ← Value Objects
│   ├── Event/            ← Domain Events
│   ├── Repository/       ← Repository Interfaces
│   └── Exception/        ← Domain Exceptions
└── Infrastructure/
    ├── Repository/       ← Repository Implementations
    ├── DoctrineType/     ← Custom Doctrine Types
    ├── EventSubscriber/  ← Infrastructure Event Subscribers
    ├── EventListener/    ← Symfony Event Listeners
    └── Bus/              ← Message Bus Implementations

Verification Checklist

When creating or reviewing a class, verify:

  1. ✅ Class Type Matches Directory (Directory X contains ONLY class type X)
  1. ✅ Class Name Follows DDD Pattern for its type
  2. ✅ Namespace Matches Directory Structure exactly
  3. ✅ Class Name Reflects Actual Functionality
  4. ✅ Correct Layer (Domain/Application/Infrastructure)
  5. ✅ Domain Layer Has NO Framework Imports (Symfony/Doctrine/API Platform)
  6. ✅ Variable Names Are Specific (not vague)
  1. ✅ Parameter Names Match Actual Types
  1. ✅ No "Helper" or "Util" Classes (extract specific responsibilities)
  2. ✅ No ad-hoc class-type suffixes/directories (Applier, Attacher, Enricher, Augmenter, Helper, Util, Manager, Service)
  3. ✅ New directories are explicit and standard, not agent-invented — must be explicitly approved by the user

PHP Best Practices

Required Patterns

Anti-Patterns (Forbidden)

Factory Pattern (Maintainability & Flexibility)

Avoid hardcoded new ClassName() in production source code — use factory methods or Factory classes

Factory Methods on Value Objects

Value objects SHOULD provide static factory methods as named constructors:

// ❌ BAD: Direct instantiation in production code
$provider = new OAuthProvider($value);

// ✅ GOOD: Factory method
$provider = OAuthProvider::fromString($value);

Factory methods (fromString(), fromArray(), create()) are the preferred way to instantiate value objects outside of their own class. The constructor remains public for use within named constructors and tests.

Collections and domain events should follow a different rule in production code: use dedicated Factory classes instead of adding static convenience constructors just to avoid new.

When Factory Classes Are REQUIRED (Production Code)

  1. Objects with injected dependencies (timestamp providers, config, etc.)
  2. Objects requiring complex construction logic
  3. Objects needing different implementations per environment
  4. Objects created from external input (DTOs, metrics, etc.)

When Direct `new` Is ACCEPTABLE

Factory Benefits

Example: Bad vs Good

// ❌ BAD: Direct instantiation with configuration
public function emit(BusinessMetric $metric): void
{
    $timestamp = (int)(microtime(true) * 1000);
    $payload = new EmfPayload(
        new EmfAwsMetadata($timestamp, new EmfCloudWatchMetricConfig(...)),
        new EmfDimensionValueCollection(...),
        new EmfMetricValueCollection(...)
    );
    $this->logger->info($payload);
}

// ✅ GOOD: Factory handles complexity
public function emit(BusinessMetric $metric): void
{
    $payload = $this->payloadFactory->createFromMetric($metric);
    $this->logger->info($payload);
}

Factory Naming Convention

Type Safety: Classes Over Arrays

Arrays are NOT allowed for collections that already have a dedicated collection type. Use the collection class instead.

Arrays lack type safety and self-documentation. Use concrete classes instead. Current CI guards specifically block bare OAuth provider collections in production code, including iterable-based variants.

Array vs Class Comparison

| Pattern | Bad (Array) | Good (Class) |

| ------------- | ----------------------------------------- | -------------------------------------------- |

| Configuration | ['endpoint' => 'X', 'operation' => 'Y'] | new EndpointOperationDimensions('X', 'Y') |

| Return data | return ['name' => $n, 'value' => $v] | return new MetricData($n, $v) |

| Method params | function emit(array $metrics) | function emit(MetricCollection $metrics) |

| Events data | ['type' => 'created', 'id' => $id] | new CustomerCreatedEvent($id) |

| Registry | private array $providers | private OAuthProviderCollection $providers |

Benefits of Typed Classes

Collection Pattern

// ❌ BAD: Array of arrays
$metrics = [
    ['name' => 'OrdersPlaced', 'value' => 1],
    ['name' => 'OrderValue', 'value' => 99.99],
];

// ✅ GOOD: Typed collection of objects
$metrics = new MetricCollection(
    new OrdersPlacedMetric(value: 1),
    new OrderValueMetric(value: 99.99)
);

When Arrays ARE Acceptable

Cross-Cutting Concerns Pattern

Use event subscribers for cross-cutting concerns (metrics, logging), NOT direct injection into handlers

Anti-Pattern: Metrics in Command Handler

// ❌ WRONG: Metrics in command handler
final class CreateCustomerHandler
{
    public function __construct(
        private CustomerRepository $repository,
        private BusinessMetricsEmitterInterface $metrics  // Wrong place!
    ) {}

    public function __invoke(CreateCustomerCommand $cmd): void
    {
        $customer = Customer::create(...);
        $this->repository->save($customer);
        $this->metrics->emit(new CustomersCreatedMetric());  // Violates SRP
    }
}

Correct Pattern: Dedicated Event Subscriber

// ✅ CORRECT: Clean command handler
final class CreateCustomerHandler
{
    public function __construct(
        private CustomerRepository $repository,
        private EventBusInterface $eventBus
    ) {}

    public function __invoke(CreateCustomerCommand $cmd): void
    {
        $customer = Customer::create(...);
        $this->repository->save($customer);
        $this->eventBus->publish(...$customer->pullDomainEvents());
        // Metrics subscriber handles emission
    }
}

// ✅ CORRECT: Metrics in dedicated subscriber
final class CustomerCreatedMetricsSubscriber implements DomainEventSubscriberInterface
{
    public function __invoke(CustomerCreatedEvent $event): void
    {
        // Error handling is automatic via DomainEventMessageHandler.
        // Subscribers are executed in async workers - failures are logged + emit metrics.
        // This ensures observability never breaks the main request (AP from CAP).
        $this->metricsEmitter->emit($this->metricFactory->create());
    }
}

Common Issues and Fixes

Issue 1: Class in Wrong Type Directory

❌ WRONG:
src/Shared/Infrastructure/Transformer/UlidValidator.php

✅ CORRECT:
src/Shared/Infrastructure/Validator/UlidValidator.php

# Fix:
mv src/Shared/Infrastructure/Transformer/UlidValidator.php \
   src/Shared/Infrastructure/Validator/UlidValidator.php
# Update namespace and all imports

Issue 2: Vague Variable Names

❌ WRONG:
private UlidTypeConverter $converter;  // Converter of what?

✅ CORRECT:
private UlidTypeConverter $typeConverter;  // Specific!

Issue 3: Misleading Parameter Names

❌ WRONG:
public function fromBinary(mixed $binary): Ulid  // Accepts mixed, not just binary

✅ CORRECT:
public function fromBinary(mixed $value): Ulid  // Accurate!

Issue 4: Helper/Util Classes

❌ WRONG:
class CustomerHelper {
    public function validateEmail() {}
    public function formatName() {}
    public function convertData() {}
}

✅ CORRECT: Extract specific responsibilities
- CustomerEmailValidator (Validator/)
- CustomerNameFormatter (Formatter/)
- CustomerDataConverter (Converter/)

Issue 5: Namespace Mismatch

❌ WRONG:
// File: src/Shared/Infrastructure/Validator/UlidValidator.php
namespace App\Shared\Infrastructure\Transformer;  // Mismatch!

✅ CORRECT:
// File: src/Shared/Infrastructure/Validator/UlidValidator.php
namespace App\Shared\Infrastructure\Validator;  // Matches directory!

Decision Tree: Where Does It Belong?

What does the class DO?

├─ Converts between types (string ↔ object)? → Converter/
├─ Transforms for DB/serialization? → Transformer/
├─ Validates values? → Validator/
├─ Builds/constructs objects? → Builder/
├─ Fixes/modifies data? → Fixer/
├─ Creates complex objects? → Factory/
├─ Resolves/determines values? → Resolver/
├─ Normalizes/serializes? → Serializer/
├─ Formats data for display? → Formatter/
├─ Maps data between structures? → Mapper/
├─ Provides data/cookies/context? → Provider/
└─ Something else? → Ask the user before creating a new directory!

Verification Commands

# Check namespace consistency
make phpcsfixer
make psalm

# Find organizational issues
grep -r "class.*Helper" src/      # Find Helper classes
grep -r "class.*Util" src/        # Find Util classes
grep -r "private.*\$converter;" src/  # Find vague names

# Verify architecture compliance
make deptrac  # Must show 0 violations

Symfony Service Configuration: No Redundant Wiring

Do not add explicit interface aliases in services.yaml when Symfony autowiring can resolve them automatically.

Rule

When an interface has exactly one implementation in src/, Symfony autowiring automatically aliases the interface to that implementation. Do NOT add a manual alias — it is redundant.

When an Explicit Alias IS Required

When an Explicit Alias is REDUNDANT (remove it)

Example

# ❌ REDUNDANT: Only one implementation exists — autowiring handles this
App\OAuth\Domain\Repository\SocialIdentityRepositoryInterface:
  alias: App\OAuth\Infrastructure\Repository\MongoDBSocialIdentityRepository

# ✅ REQUIRED: Two implementations exist — must disambiguate
App\User\Domain\Repository\UserRepositoryInterface:
  alias: App\User\Infrastructure\Repository\CachedUserRepository

Explicit Constructor Arguments Are Still Needed

Even when the alias is redundant, you may still need an explicit service definition for constructor arguments that autowiring cannot resolve (e.g., non-type-hinted parameters, named service references):

# ✅ NEEDED: $oauthRedis is a named Redis connection, not autowirable
App\OAuth\Infrastructure\Repository\RedisOAuthStateRepository:
  arguments:
    $oauthRedis: '@oauth.redis_connection'
# ❌ NOT NEEDED: the interface alias (autowiring resolves it)
# App\OAuth\Domain\Repository\OAuthStateRepositoryInterface:
#   alias: App\OAuth\Infrastructure\Repository\RedisOAuthStateRepository

Verification

# Check that autowiring resolves the interface correctly
docker compose exec php bin/console debug:container <InterfaceName>
# Should show "This service is a private alias for the service <Implementation>"

Constraints (Never Do This)

NEVER:

ALWAYS:

Related Skills

Hardcoded Configuration Values → `.env` Extraction

Configurable values (TTLs, timeouts, limits, sizes, batch counts) belong in .env, not as class constants.

When to Extract

Extract a constant to .env when it represents:

When NOT to Extract

Keep as constants when the value is:

Extraction Pattern (3-Step)

Step 1: Add env variable to .env and .env.test

# .env
CACHE_USER_BY_ID_TTL=600
CACHE_USER_BY_EMAIL_TTL=300

# .env.test (same or test-appropriate value)
CACHE_USER_BY_ID_TTL=600
CACHE_USER_BY_EMAIL_TTL=300

Step 2: Bind in config/services.yaml

App\User\Infrastructure\Repository\CachedUserRepository:
  arguments:
    $ttlById: '%env(int:CACHE_USER_BY_ID_TTL)%'
    $ttlByEmail: '%env(int:CACHE_USER_BY_EMAIL_TTL)%'

Step 3: Replace constant with constructor parameter

// ❌ BEFORE: Hardcoded constant
final class CachedUserRepository
{
    private const TTL_BY_ID = 600;
    private const TTL_BY_EMAIL = 300;
}

// ✅ AFTER: Injected from .env
final readonly class CachedUserRepository
{
    public function __construct(
        private UserRepositoryInterface $inner,
        private CacheInterface $cache,
        private int $ttlById,
        private int $ttlByEmail,
    ) {
    }
}

Common Extraction Candidates

| Pattern in Source | Extract To .env |

| ----------------------------------------- | -------------------------------------- |

| private const TTL_* = <seconds> | CACHE_*_TTL=<seconds> |

| private const EXPIRES_AFTER_* = <value> | TOKEN_EXPIRATION_SECONDS=<value> |

| private const MAX_ATTEMPTS = <n> | *_MAX_ATTEMPTS=<n> |

| private const BATCH_SIZE = <n> | *_BATCH_SIZE=<n> |

| private const DEFAULT_*_SECONDS = <n> | *_SECONDS=<n> |

| Constructor default = 900 | Remove default, bind via services.yaml |

Verification After Extraction

make phpcsfixer          # Fix code style
make psalm               # Verify type safety
make unit-tests          # Ensure tests pass (update mocks for new constructor params)
make integration-tests   # Verify runtime binding works
make ci                  # Full validation

CI Integration: When CI Fails

When make ci fails, consult this skill if the failure involves:

| CI Failure Indicator | Code Organization Fix |

| ------------------------------------ | --------------------------------------------------- |

| Class not found / namespace mismatch | Verify namespace matches directory structure |

| Deptrac violation after moving class | Check layer placement (Domain/Application/Infra) |

| PHPInsights architecture score drop | Verify "Directory X contains ONLY class type X" |

| Psalm type errors after refactoring | Check that imports and namespaces were all updated |

| Test failures after class move | Move test file too, update test namespace + imports |

Refactoring Checklist (Before Running CI)

When moving, renaming, or restructuring classes:

Related Documentation

See reference/troubleshooting.md for detailed troubleshooting and examples/organization-fixes.md for real-world examples.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.