Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Doctrine Types Bundle Laravel Package

assoconnect/doctrine-types-bundle

Symfony bundle integrating Symfony Validator with Doctrine custom DBAL types to avoid duplicate validation/mapping code. Includes common value-object types (money/amount, IBAN/BIC, email, phone, country/currency, locale/timezone, IDs) with nullable and non-nullable support.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for Laravel

  1. Install the Bundle (via Composer):

    composer require assoconnect/doctrine-types-bundle
    

    Note: Requires PHP 8.4+ and Symfony components (e.g., symfony/validator).

  2. Register the Bundle (in config/app.php):

    'extra' => [
        'bundles' => [
            Assoconnect\DoctrineTypesBundle\AssoconnectDoctrineTypesBundle::class => ['all' => true],
        ],
    ],
    
  3. Configure Doctrine DBAL (in config/doctrine.php):

    'dbal' => [
        'types' => [
            'amount' => Assoconnect\DoctrineTypesBundle\DBAL\Types\AmountType::class,
            'spanish_nif' => Assoconnect\DoctrineTypesBundle\DBAL\Types\SpanishNifType::class,
            // Add other types as needed
        ],
    ],
    
  4. First Use Case: Spanish NIF Validation Update a migration to use the new type:

    Schema::create('clients', function (Blueprint $table) {
        $table->string('nif')->type('spanish_nif'); // Uses SpanishNifType
        $table->timestamps();
    });
    

Implementation Patterns

Workflow: Type-Driven Development

  1. Define Entity Properties Use Doctrine types in your model (via annotations or YAML/XML):

    /**
     * @ORM\Column(type="spanish_nif")
     */
    private string $nif;
    
  2. Leverage Built-in Validation The bundle auto-integrates with Symfony’s validator. For Laravel, manually map constraints:

    use Illuminate\Validation\Rule;
    
    $rules = [
        'nif' => ['required', Rule::custom(function ($attribute, $value) {
            return SpanishNifType::validate($value); // Reuse type logic
        })],
    ];
    
  3. Custom Type Extension Extend existing types (e.g., for locale-specific rules):

    class CustomSpanishNifType extends SpanishNifType {
        public function getSQLDeclaration(array $column, AbstractPlatform $platform) {
            return 'VARCHAR(255) COMMENT \'Custom Spanish NIF\'';
        }
    }
    
  4. Query Optimization Use native types in raw queries:

    DB::select('SELECT * FROM clients WHERE nif = ?', ['12345678A']);
    

Integration Tips

  • For Eloquent Models: Use laravel-doctrine/orm to bridge Doctrine types to Eloquent.
  • For Validation: Create a Laravel rule object wrapping the type’s validation:
    class SpanishNifRule extends Rule {
        public function validate($attribute, $value, $fail) {
            if (!SpanishNifType::validate($value)) {
                $fail('Invalid Spanish NIF.');
            }
        }
    }
    
  • For Migrations: Prefer type() over string() for type safety:
    $table->string('iban')->type('iban'); // Uses IbanType
    

Gotchas and Tips

Pitfalls

  1. PHP Version Mismatch

    • Issue: Bundle requires PHP 8.4+. Laravel 9.x (PHP 8.1/8.2) will fail.
    • Fix: Use a fork or manually patch the bundle’s composer.json.
  2. Validation System Conflict

    • Issue: Symfony’s validator is not natively supported in Laravel.
    • Fix: Replace Symfony constraints with Laravel’s Validator::extend() or custom rules.
  3. ORM vs. DBAL Confusion

    • Issue: Doctrine ORM requires laravel-doctrine/orm; DBAL-only usage may miss type mappings.
    • Fix: Explicitly register types in config/doctrine.php under dbal.types.
  4. Type-Specific Edge Cases

    • Issue: SpanishNifType may not cover all business rules (e.g., historical formats).
    • Fix: Extend the type or add custom validation layers.

Debugging

  • Type Registration Errors: Check if the bundle is enabled in config/bundles.php and types are listed in config/doctrine.php.

    php bin/console debug:container assoconnect_doctrine_types
    
  • Validation Failures: Use SpanishNifType::validate() directly to debug:

    var_dump(SpanishNifType::validate('12345678Z')); // Returns bool
    

Extension Points

  1. Add Custom Types Create a new type class (e.g., MyCustomType) and register it in config/doctrine.php:

    'types' => [
        'my_custom_type' => App\Doctrine\DBAL\Types\MyCustomType::class,
    ],
    
  2. Override Default Behavior Extend existing types (e.g., MoneyType) to modify SQL generation or validation:

    class CustomMoneyType extends MoneyType {
        public function convertToDatabaseValue($value, AbstractPlatform $platform) {
            return round($value, 2); // Force 2 decimal places
        }
    }
    
  3. Laravel-Specific Wrappers Create a facade to abstract Doctrine types:

    class DoctrineTypeFacade {
        public static function validateSpanishNif(string $nif): bool {
            return SpanishNifType::validate($nif);
        }
    }
    

Performance Tips

  • Avoid Overuse: Custom types add query parsing overhead. Use only for critical fields (e.g., iban, nif).
  • Benchmark: Test with EXPLAIN ANALYZE to compare custom types vs. native VARCHAR.
  • Cache Validation: Cache results of Type::validate() for repeated checks.

Configuration Quirks

  • Nullable Fields: The bundle supports nullable types out of the box. Ensure your Doctrine entity annotations reflect this:
    /**
     * @ORM\Column(type="spanish_nif", nullable=true)
     */
    private ?string $nif = null;
    
  • Case Sensitivity: Some types (e.g., EmailType) are case-insensitive by default. Override if needed:
    class CaseSensitiveEmailType extends EmailType {
        public function convertToDatabaseValue($value, AbstractPlatform $platform) {
            return strtoupper($value);
        }
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky