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

Mapper Bundle Laravel Package

cmath10/mapper-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require cmath10/mapper-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Cmath10\MapperBundle\Cmath10MapperBundle::class => ['all' => true],
    ];
    
  2. Basic Usage Define a mapper class (e.g., src/Mapper/UserMapper.php):

    namespace App\Mapper;
    
    use Cmath10\MapperBundle\Mapper\MapperInterface;
    use App\Entity\User;
    
    class UserMapper implements MapperInterface
    {
        public function map(array $data): User
        {
            return (new User())
                ->setName($data['name'])
                ->setEmail($data['email']);
        }
    }
    
  3. First Use Case Inject the mapper via Symfony’s dependency injection:

    use App\Mapper\UserMapper;
    
    class UserController
    {
        public function __construct(private UserMapper $userMapper) {}
    
        public function create(Request $request)
        {
            $data = $request->request->all();
            $user = $this->userMapper->map($data);
            // Persist $user...
        }
    }
    

Implementation Patterns

Core Workflows

  1. DTO-to-Entity Mapping Useful for decoupling API input from domain models:

    $dto = new UserDto($request->all());
    $user = $this->userMapper->map($dto->toArray());
    
  2. Collection Mapping Extend MapperInterface to handle arrays of data:

    public function mapCollection(array $data): array
    {
        return array_map([$this, 'map'], $data);
    }
    
  3. Service Integration Combine with Symfony’s Serializer or Validator:

    use Symfony\Component\Serializer\SerializerInterface;
    
    class UserMapper implements MapperInterface
    {
        public function __construct(private SerializerInterface $serializer) {}
    
        public function map(array $data): User
        {
            $entity = $this->serializer->deserialize(
                json_encode($data),
                User::class,
                'json'
            );
            return $entity;
        }
    }
    

Best Practices

  • Naming Conventions: Prefix mappers with EntityNameMapper (e.g., ProductMapper).
  • Dependency Injection: Prefer constructor injection for external services (e.g., Validator, Serializer).
  • Validation: Validate input data before mapping (e.g., using Symfony’s ValidatorInterface).

Gotchas and Tips

Common Pitfalls

  1. Circular References If mapping nested entities, ensure bidirectional relationships are handled:

    // Avoid infinite loops in __toString() or getters.
    
  2. Type Safety The package lacks built-in type hints for mapped properties. Add PHPDoc or runtime checks:

    if (!isset($data['email'])) {
        throw new \InvalidArgumentException('Email is required.');
    }
    
  3. Configuration Overrides The bundle has minimal config. Override services in config/packages/cmath10_mapper.yaml if needed:

    services:
        App\Mapper\UserMapper:
            tags: ['mapper']
    

Debugging Tips

  • Log Mapped Data: Add debug logs to verify input/output:
    \Log::debug('Mapping data:', $data);
    
  • Use var_dump(): For complex objects, dump intermediate states:
    var_dump($this->mapper->map($data));
    

Extension Points

  1. Custom Mapper Tags Tag mappers for autowiring (if extending the bundle):

    # config/services.yaml
    services:
        App\Mapper\CustomMapper:
            tags: ['mapper.custom']
    
  2. Event Listeners Trigger events before/after mapping (e.g., for logging or transformations):

    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class MappingSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                'mapper.pre_map' => 'onPreMap',
                'mapper.post_map' => 'onPostMap',
            ];
        }
    }
    
  3. Performance For large datasets, cache mappers or use mapCollection with batch processing:

    $batchSize = 100;
    foreach (array_chunk($data, $batchSize) as $batch) {
        $this->mapper->mapCollection($batch);
    }
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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