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

Transfer Object Converter Laravel Package

bornfight/transfer-object-converter

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bornfight/transfer-object-converter
    
  2. Register the Service Provider (if not auto-discovered): Add to config/app.php under providers:

    Bornfight\TransferObjectConverter\TransferObjectConverterServiceProvider::class,
    
  3. Define a Transfer Object (DTO): Create a class with public properties matching incoming request data:

    namespace App\DTO;
    
    class UserCreateRequest
    {
        public string $name;
        public string $email;
        public int $age;
    }
    
  4. First Use Case: In a controller, inject the converter and populate the DTO:

    use Bornfight\TransferObjectConverter\TransferObjectConverter;
    
    public function store(TransferObjectConverter $converter)
    {
        $dto = new UserCreateRequest();
        $converter->convert($dto); // Populates $dto with request data
    
        // Use $dto->name, $dto->email, etc.
    }
    

Where to Look First

  • USAGE.md (Official docs)
  • src/TransferObjectConverter.php (Core logic)
  • tests/ (Usage examples and edge cases)

Implementation Patterns

Core Workflow: DTO Population

  1. Define DTOs: Use classes with public properties to mirror request payloads.

    class LoginRequest {
        public string $username;
        public string $password;
        public bool $rememberMe = false;
    }
    
  2. Controller Integration:

    public function login(TransferObjectConverter $converter)
    {
        $request = new LoginRequest();
        $converter->convert($request);
    
        // Validate or process $request
    }
    
  3. Nested Objects: Support nested DTOs by ensuring properties are objects:

    class UserProfileRequest {
        public string $bio;
        public Address $address; // Another DTO
    }
    

Advanced Patterns

1. Validation Integration

Combine with Laravel Validation:

$converter->convert($dto);
$validator = Validator::make($dto, [
    'email' => 'required|email',
    'age' => 'integer|min:18',
]);

2. Type Safety

Leverage PHP 7.4+ typed properties:

class OrderRequest {
    public string $productId;
    public float $quantity;
    public array $options = [];
}

3. Partial Population

Skip properties by setting them to null or using convert() with a whitelist:

$converter->convert($dto, ['name', 'email']); // Only populate these fields

4. API Resource Conversion

Convert API responses back to DTOs:

$responseDto = new ApiResponse();
$converter->convert($responseDto, $apiResponseData);

5. Form Requests

Extend FormRequest and use the converter:

class StoreUserRequest extends FormRequest {
    public function rules() { ... }

    public function prepareForConversion()
    {
        $this->merge([
            'age' => (int) $this->age,
        ]);
    }
}

6. Middleware for Global Conversion

Create middleware to auto-convert DTOs:

public function handle($request, Closure $next)
{
    if ($request->has('dto_class')) {
        $dto = new $request->dto_class();
        $converter->convert($dto);
        $request->merge((array) $dto);
    }
    return $next($request);
}

Gotchas and Tips

Pitfalls

  1. Property Naming Mismatches:

    • The converter uses case-sensitive property names. Ensure they match the request payload exactly (e.g., user_name vs. userName).
    • Fix: Use convert() with a custom mapping:
      $converter->convert($dto, [], [
          'user_name' => 'userName',
      ]);
      
  2. Non-Public Properties:

    • Only public properties are populated. Protected/private properties are ignored.
    • Fix: Use getters/setters or make properties public.
  3. Circular References:

    • Nested DTOs with circular references (e.g., User has Address, Address has User) will cause infinite loops.
    • Fix: Avoid circular references or use lazy loading.
  4. Type Coercion Issues:

    • The converter does no type casting by default. A request field age=abc will set $dto->age = "abc".
    • Fix: Cast manually or extend the converter:
      $dto->age = (int) $request->input('age');
      
  5. Overwriting Existing Data:

    • convert() overwrites existing property values. Use with caution in partial updates.
    • Fix: Merge data first:
      $dto->email = $existingEmail; // Preserve existing
      $converter->convert($dto, ['name', 'age']);
      
  6. Large Payloads:

    • Deeply nested or large payloads may hit recursion limits.
    • Fix: Increase xdebug.max_nesting_level or flatten the DTO structure.

Debugging Tips

  1. Enable Debug Mode: Set TRANSFER_OBJECT_CONVERTER_DEBUG=true in .env to log conversion issues.

  2. Check Request Data: Dump the raw request to verify payload structure:

    dd($request->all());
    
  3. Validate DTO Structure: Use get_object_vars() to inspect populated DTOs:

    dd(get_object_vars($dto));
    
  4. Test Edge Cases:

    • Empty payloads: $converter->convert($dto, [])
    • Null values: Ensure DTO properties can handle null.
    • Malformed JSON: Use json_decode($request->getContent(), true) first.

Configuration Quirks

  1. Service Provider Auto-Discovery:

    • The package should auto-discover if using Laravel ≥5.5. If missing, manually register the provider.
  2. Binding Custom Converters: Bind a custom converter in AppServiceProvider:

    $this->app->bind(TransferObjectConverter::class, function ($app) {
        return new CustomTransferObjectConverter();
    });
    
  3. Environment Variables:

    • No built-in config file, but you can extend the converter to read from config():
      $converter->setStrictMode(config('transfer_object_converter.strict', false));
      

Extension Points

  1. Custom Converters: Extend TransferObjectConverter to add logic:

    class CustomConverter extends TransferObjectConverter {
        protected function convertProperty($dto, $property, $value) {
            if ($property === 'age') {
                return (int) $value;
            }
            return parent::convertProperty($dto, $property, $value);
        }
    }
    
  2. Pre/Post Conversion Hooks: Use events or middleware to modify DTOs before/after conversion:

    // Example: Sanitize input
    $converter->convert($dto);
    $dto->email = filter_var($dto->email, FILTER_SANITIZE_EMAIL);
    
  3. Support for Arrays: Extend to handle array-shaped DTOs:

    class ArrayDto {
        public array $items = [];
    }
    
  4. Integration with API Platform: Use for serializing/deserializing API resources:

    $converter->convert($resource, $apiData);
    

Performance Tips

  1. Avoid Deep Nesting: Flatten complex DTOs to reduce recursion overhead.

  2. Reuse DTO Instances: Instantiate DTOs once and reuse them (e.g., in a service layer).

  3. Cache Converters: For high-traffic APIs, cache converter instances:

    $converter = app(TransferObjectConverter::class);
    Cache::remember('converter', 60, fn() => $converter);
    
  4. Use convert() Selectively: Pass only the needed properties to avoid unnecessary processing:

    $converter->convert($dto, ['email', 'name']); // Instead of all properties
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware