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

Object Mapper Laravel Package

symfony/object-mapper

Symfony Object Mapper component maps data from one object to another using PHP attributes. Simplifies DTO/entity transformations, supports configurable mapping rules, and integrates with the Symfony ecosystem. Documentation and contributions are handled in the main Symfony repository.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Symfony Ecosystem Alignment: Seamlessly integrates with Symfony components (e.g., DependencyInjection, HttpFoundation, Messenger), making it ideal for Laravel projects already leveraging Symfony integrations (e.g., API Platform, HTTP clients, or DI containers).
  • Attribute-Driven Design: Leverages PHP 8+ attributes (#[MapEntity], #[Ignore]) for declarative mapping, reducing boilerplate in controllers/services. Aligns with Laravel’s growing adoption of attributes (e.g., #[AsRequest], #[AsResponse] in API resources).
  • Domain-Driven Design (DDD) Support: Enables clean separation between domain entities, DTOs, and API contracts, critical for microservices or layered architectures.
  • Nested/Collection Mapping: Handles complex structures (e.g., nested objects, collections) via CollectionTransformer, reducing manual recursion in mapping logic.
  • Laravel Compatibility: While not Laravel-native, it integrates via Symfony’s DependencyInjection or standalone usage, avoiding framework lock-in.

Integration Feasibility

  • Laravel Service Provider: Can be bootstrapped via a Laravel service provider to register the ObjectMapper as a singleton, replacing manual instantiation.
  • Attribute Integration: Works alongside Laravel’s existing attribute system (e.g., #[AsRequest]) with minimal conflict risk.
  • Symfony DI Compatibility: If using symfony/dependency-injection (e.g., via Laravel packages like spatie/laravel-symfony), the mapper can be auto-wired into services.
  • Standalone Usage: Can be used in non-DI contexts (e.g., controllers) via direct instantiation, though DI integration is recommended for testability.

Technical Risk

  • PHP 8+ Requirement: Attributes are mandatory for full functionality; projects on PHP 7.x or without attribute support will need polyfills or alternatives.
  • Learning Curve: Developers must adopt attribute-based mapping (e.g., #[MapProperty]) instead of traditional manual mapping, requiring training or documentation.
  • Performance Overhead: Attribute reflection and runtime mapping may introduce minor overhead for high-throughput APIs. Benchmark against alternatives like spatie/laravel-data or manual mapping.
  • Symfony Dependency: While lightweight, the package ties the project to Symfony’s ecosystem (e.g., for future features like ConditionCallableInterface). Mitigate by evaluating standalone alternatives if Symfony adoption is limited.
  • Edge Cases: Complex scenarios (e.g., circular references, dynamic properties) may require custom transforms or fallbacks to manual mapping.

Key Questions

  1. PHP Version: Is the project on PHP 8.1+? If not, can attributes be polyfilled (e.g., via nikic/php-parser)?
  2. Symfony Adoption: Does the project already use Symfony components (e.g., DI, HTTP)? If not, is standalone usage acceptable?
  3. Mapping Complexity: Are there frequent nested/collection mappings, or will simple DTO transformations suffice (simpler alternatives may exist)?
  4. Laravel Integration: Should the mapper be tightly coupled to Laravel’s DI (e.g., via a service provider) or kept standalone?
  5. Performance Needs: Are there throughput requirements that necessitate benchmarking against alternatives like Mapperly or JMS Serializer?
  6. Attribute Adoption: Is the team comfortable with attribute-based mapping, or will manual configuration (e.g., YAML/XML) be preferred?
  7. Testing Impact: How will the mapper affect unit/integration tests? Will mocking or DI containers simplify testing?
  8. Future-Proofing: Are there plans to adopt Symfony’s ecosystem (e.g., API Platform, Messenger)? If not, is a Laravel-native alternative (e.g., spatie/laravel-data) more suitable?

Integration Approach

Stack Fit

  • Primary Use Cases:
    • API Layer: Map between Laravel models (e.g., User) and DTOs (e.g., UserResponseDTO) in controllers/resources.
    • Domain Layer: Transform between entities, commands, and events (e.g., OrderCreatedEventOrderCommand).
    • Legacy Systems: Bridge outdated database schemas to modern Laravel models.
    • Testing: Generate test data by mapping between fixtures and application objects.
  • Symfony Integration Points:
    • Dependency Injection: Register ObjectMapper as a Laravel service for auto-wiring.
    • HTTP Components: Use with symfony/http-foundation for request/response mapping.
    • Messenger: Map between messages in event-driven architectures.
  • Laravel-Specific Considerations:
    • Service Provider: Bootstrap the mapper in AppServiceProvider or a dedicated ObjectMapperServiceProvider.
    • Attribute Conflicts: Ensure compatibility with Laravel’s attributes (e.g., #[AsRequest]) by namespace isolation.
    • Eloquent Integration: Avoid mapping Eloquent models directly to DTOs; use a separate layer (e.g., UserEntityUserDTO).

Migration Path

  1. Pilot Phase:
    • Start with a single high-impact use case (e.g., API response DTOs).
    • Replace manual mapping in one controller/resource (e.g., UserController).
    • Compare development time and code quality against manual mapping.
  2. Incremental Adoption:
    • Add attributes to existing DTOs (e.g., #[MapEntity], #[Ignore]).
    • Gradually replace manual mapping in services/commands.
    • Introduce custom transforms for complex edge cases.
  3. Full Integration:
    • Register ObjectMapper in Laravel’s DI container.
    • Replace global mapping logic (e.g., array_map in controllers) with attribute-driven mapping.
    • Deprecate legacy mapping utilities (e.g., MapperHelper).

Compatibility

  • Laravel Versions: Compatible with Laravel 9+ (PHP 8.1+) due to attribute support. For older versions, evaluate polyfills or alternatives.
  • Symfony Components: Works with Symfony 6.4+/8.x. Ensure no version conflicts with other Symfony packages.
  • Third-Party Packages: May conflict with other mappers (e.g., JMS Serializer, spatie/laravel-data). Audit dependencies to avoid duplication.
  • Custom Logic: Supports custom transforms via Callable or ObjectMapperAwareInterface, allowing integration with Laravel-specific logic (e.g., query scopes, accessors).

Sequencing

  1. Prerequisites:
    • Upgrade to PHP 8.1+ if necessary.
    • Ensure Symfony components (if used) are compatible.
  2. Core Setup:
    • Install the package: composer require symfony/object-mapper.
    • Register the mapper in Laravel’s DI (e.g., via service provider).
  3. Attribute Adoption:
    • Add #[MapEntity] to DTOs and map source entities.
    • Use #[MapProperty], #[Ignore], etc., for fine-grained control.
  4. Testing:
    • Write unit tests for mapped DTOs (mock ObjectMapper if needed).
    • Test edge cases (e.g., missing properties, nested objects).
  5. Performance Tuning:
    • Benchmark critical paths (e.g., API response generation).
    • Optimize with caching (e.g., #[CacheAttributes] in Symfony 8+).
  6. Documentation:
    • Update team docs with mapping conventions (e.g., attribute usage, custom transforms).
    • Train developers on attribute-based mapping.

Operational Impact

Maintenance

  • Pros:
    • Reduced Boilerplate: Attributes centralize mapping logic, making it easier to update (e.g., adding a new field to a DTO).
    • Consistent Rules: Mapping logic is enforced via attributes, reducing ad-hoc code in controllers/services.
    • Symfony Backing: Benefits from Symfony’s long-term support and community (e.g., bug fixes, security patches).
  • Cons:
    • Attribute Management: Changes to mapping rules require attribute updates, which may trigger reflection overhead.
    • Debugging Complexity: Nested mapping issues (e.g., circular references) can be harder to debug than manual code.
    • Dependency Updates: Requires monitoring Symfony’s release cycle for breaking changes.

Support

  • Pros:
    • Community Resources: Leverage Symfony’s documentation, Stack Overflow, and GitHub issues.
    • Laravel Ecosystem: Potential for Laravel-specific plugins or wrappers (e.g., laravel-object-mapper).
    • Attribute Clarity: Declarative mapping reduces "works on my machine" issues by making rules explicit.
  • Cons:
    • Limited Laravel-Specific Support: Issues may require workarounds for Laravel quirks (e.g., Eloquent hydration).
    • Symfony Knowledge Gap: Developers unfamiliar with Symfony may need training on the mapper’s features (e.g., ConditionCallableInterface).

Scaling

  • Performance:
    • Attribute Reflection: Initial overhead for attribute parsing, but cached in Symfony 8+ (#[CacheAttributes]).
    • Mapping Throughput: Benchmark for high-load APIs; consider alternatives like Mapperly if performance is critical.
    • Memory Usage: Nested/collection mapping may increase memory usage; optimize with lazy loading or
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata