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

Auto Mapper Plus Laravel Package

mark-gerarts/auto-mapper-plus

AutoMapper+ transfers data between PHP objects with minimal boilerplate, inspired by .NET AutoMapper. Define mappings with custom callbacks and operations, handle nested objects, construction, naming conventions, and map arrays/stdClass with configurable options.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:

    • Laravel Alignment: AutoMapper+ is a natural fit for Laravel applications where DTOs, view models, and API responses are common. It reduces boilerplate in data transformation layers (e.g., controllers, services, or repositories).
    • Domain-Driven Design (DDD) Support: Aligns with Laravel’s ecosystem (e.g., Eloquent models → DTOs, API resources) and DDD principles (e.g., mapping entities to domain objects or aggregates).
    • Flexibility: Supports custom callbacks, nested mappings, and polymorphic types, which are critical for complex Laravel applications (e.g., multi-tenancy, inheritance hierarchies).
    • Private Property Access: Laravel’s Eloquent models often use private properties; AutoMapper+ can map these without reflection hacks or getter/setter overhead.
    • Integration with Laravel Services: Can be injected into Laravel’s service container (via bind()) for dependency injection, mirroring Laravel’s native DI patterns.
  • Cons:

    • No Native Laravel Integration: Unlike Symfony’s AutoMapper+ bundle, this package lacks Laravel-specific features (e.g., service provider bootstrapping, config integration). Requires manual setup.
    • Performance Overhead: Reflection-based property mapping may introduce latency in high-throughput APIs (e.g., real-time systems). Benchmarking is recommended for critical paths.
    • Tight Coupling Risk: Overuse of AutoMapper+ could lead to opaque mappings, making debugging harder (e.g., "Why is User::class mapped to UserDto::class with these transformations?").

Integration Feasibility

  • Laravel Stack Compatibility:
    • PHP 8.1+: AutoMapper+ supports modern PHP features (e.g., named arguments, constructor property promotion), aligning with Laravel’s PHP version requirements.
    • Composer: Installable via Packagist; no conflicts with Laravel’s core dependencies.
    • Service Container: Can be registered as a singleton or context-bound instance in Laravel’s container.
    • Testing: Works with Laravel’s testing tools (e.g., Mockery for mocking mappers, Pest/PHPUnit for assertions).
  • Database/ORM Integration:
    • Eloquent: Can map Eloquent models to DTOs/DTOs to API resources (e.g., UserUserResource).
    • Query Builder: Useful for transforming raw query results (e.g., DB::select() → structured responses).
  • API Layer:
    • Fractal/Spatie Laravel API Resources: AutoMapper+ can pre-process data before serialization (e.g., flatten nested relationships).
    • GraphQL: Complements packages like rebing/graphql-laravel for resolving complex types.

Technical Risk

  • Critical Risks:
    • Mapping Errors: Incorrectly configured mappings (e.g., circular references, missing properties) may cause runtime exceptions. Requires robust testing (e.g., property-based testing with pest).
    • Performance: Reflection-heavy operations could impact Laravel’s request lifecycle. Profile with tools like Xdebug or Blackfire.
    • Maintenance Debt: Custom operations or complex mappings may become hard to maintain. Document mappings explicitly (e.g., in a MappingRegistry class).
  • Mitigation Strategies:
    • Validation: Use Laravel’s ValidatesWhenResolved or custom validation rules to ensure source objects meet mapping requirements.
    • Caching: Cache compiled mappings (if AutoMapper+ supports it) or use Laravel’s cache layer for frequently used mappings.
    • Monitoring: Log mapping failures (e.g., via Laravel’s Log facade) and alert on anomalies.
    • Fallbacks: Implement graceful degradation (e.g., return partial DTOs if mapping fails).

Key Questions

  1. Adoption Scope:
    • Will AutoMapper+ replace all manual DTO mappings, or only specific cases (e.g., API responses)?
    • How will it interact with existing Laravel packages (e.g., spatie/laravel-data, laravel-shift/doctrine-types)?
  2. Performance:
    • What is the acceptable latency for mapping operations in our API?
    • Are there bottlenecks in current manual mappings that AutoMapper+ could resolve?
  3. Testing:
    • How will we test mappings? Unit tests for individual mappings? Integration tests for full workflows?
    • Will we use property-based testing to validate edge cases (e.g., null values, nested objects)?
  4. Tooling:
    • Can we integrate AutoMapper+ with Laravel’s IDE tools (e.g., PHPStorm’s "Go to Implementation") for better developer experience?
    • Will we generate mapping configurations from annotations (e.g., using phpdocumentor)?
  5. Long-Term Viability:
    • Is the package actively maintained? (Last release: 2025-12-24, but check GitHub activity.)
    • Are there plans to add Laravel-specific features (e.g., service provider integration)?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Service Container: Register AutoMapper+ as a singleton or context-bound instance:
      $app->bind(AutoMapperInterface::class, function ($app) {
          $config = new AutoMapperConfig();
          // Register mappings here or via config files.
          return new AutoMapper($config);
      });
      
    • Config Files: Store mappings in Laravel’s config/automapper.php for environment-specific overrides.
    • Service Providers: Bootstrap mappings in a dedicated provider (e.g., App\Providers\AutoMapperServiceProvider).
  • API Layer:
    • Resources: Use AutoMapper+ to transform Eloquent models → API resources before serialization.
    • GraphQL: Resolve complex types via custom operations (e.g., MapFrom with GraphQL field resolvers).
  • Domain Layer:
    • DTOs: Map entities to domain objects for business logic (e.g., UserEntityUserDomainObject).
    • Commands/Queries: Transform input DTOs to domain commands (e.g., CreateUserRequestCreateUserCommand).

Migration Path

  1. Pilot Phase:
    • Start with non-critical mappings (e.g., API responses, internal DTOs).
    • Compare performance/boilerplate reduction against manual mappings.
  2. Incremental Adoption:
    • Step 1: Replace simple 1:1 property mappings (e.g., UserUserDto).
    • Step 2: Introduce custom operations for complex logic (e.g., age calculation).
    • Step 3: Adopt nested mappings (e.g., PostPostResource with AuthorResource).
    • Step 4: Replace manual collection mappings (e.g., User::all()UserResource::collection()).
  3. Tooling:
    • Write a script to auto-generate basic mappings from existing DTOs (e.g., using ReflectionClass).
    • Use Laravel’s make:command to validate existing mappings against AutoMapper+ rules.

Compatibility

  • Laravel Versions: Tested with Laravel 10+ (PHP 8.1+). May require adjustments for older versions.
  • Dependencies:
    • Conflicts: None expected, but check for version constraints (e.g., symfony/options-resolver).
    • Extensions: Works with Laravel’s core packages (e.g., Eloquent, HTTP, Validation).
  • Third-Party Packages:
    • API Resources: Complements spatie/laravel-api-resources for serialization.
    • GraphQL: Integrates with rebing/graphql-laravel for type resolution.
    • Testing: Compatible with pestphp/pest, mockery/mockery, and laravel/testbench.

Sequencing

  1. Setup:
    • Install the package: composer require mark-gerarts/auto-mapper-plus.
    • Register the mapper in AppServiceProvider or a dedicated provider.
  2. Configuration:
    • Define mappings in config/automapper.php or via code.
    • Example:
      'mappings' => [
          App\Models\User::class => App\DTO\UserDto::class,
          App\Models\Post::class => App\DTO\PostDto::class,
      ],
      'operations' => [
          App\DTO\UserDto::class => [
              'age' => Operation::mapFrom(fn ($user) => now()->year - $user->birth_year),
          ],
      ],
      
  3. Usage:
    • Inject AutoMapperInterface into services/controllers.
    • Replace manual DTO assignments with $mapper->map($entity, Dto::class).
  4. Testing:
    • Write unit tests for each mapping (e.g., UserTesttestMapUserToDto).
    • Use Laravel’s RefreshDatabase trait for integration tests.
  5. Monitoring:
    • Log mapping failures (e.g., try-catch blocks around $mapper->map()).
    • Set up Laravel’s failed-job monitoring for async mapping tasks.

Operational Impact

Maintenance

  • **Pro
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours