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

Dto Management Laravel Package

solido/dto-management

Manage, discover, and enhance DTOs in PHP apps with Solido DTO Management. Provides tools to register and locate DTO classes and apply enhancements consistently across your codebase. Documentation and contribution guides available.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require solido/dto-management
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Solido\DTOManagement\DTOManagementServiceProvider"
    
  2. Define a DTO Create a class extending Solido\DTOManagement\DTO:

    namespace App\DTO;
    
    use Solido\DTOManagement\DTO;
    
    class UserDTO extends DTO
    {
        public string $name;
        public int $age;
    }
    
  3. Register DTOs In config/dto-management.php, add your DTOs under the dto key:

    'dto' => [
        'App\DTO\UserDTO' => [
            'version' => '1.0',
            'description' => 'User data transfer object',
        ],
    ],
    
  4. First Use Case: Fetching a DTO

    use Solido\DTOManagement\Facades\DTOManager;
    
    $userDTO = DTOManager::getDTO('App\DTO\UserDTO');
    $userDTO->name = 'John Doe';
    $userDTO->age = 30;
    

Implementation Patterns

Core Workflows

  1. DTO Versioning

    • Define versions in config/dto-management.php:
      'App\DTO\UserDTO' => [
          'versions' => [
              '1.0' => ['fields' => ['name', 'age']],
              '2.0' => ['fields' => ['name', 'age', 'email']],
          ],
      ],
      
    • Fetch a specific version:
      $userDTO = DTOManager::getDTO('App\DTO\UserDTO', '2.0');
      
  2. DTO Enhancement Extend DTOs dynamically with traits or methods:

    namespace App\DTO;
    
    use Solido\DTOManagement\DTO;
    use Solido\DTOManagement\Enhancer\DTOEnhancer;
    
    class UserDTO extends DTO
    {
        public string $name;
    
        public function fullName(): string
        {
            return "User: {$this->name}";
        }
    }
    
    // Register enhancer in config:
    'enhancers' => [
        'App\DTO\UserDTO' => [
            'App\DTO\Enhancers\UserEnhancer',
        ],
    ],
    
  3. DTO Validation Use built-in validation rules:

    class UserDTO extends DTO
    {
        public string $name;
        public int $age;
    
        protected function rules(): array
        {
            return [
                'name' => 'required|string|max:255',
                'age' => 'required|integer|min:18',
            ];
        }
    }
    
  4. DTO Serialization Convert DTOs to arrays or JSON:

    $userDTO = DTOManager::getDTO('App\DTO\UserDTO');
    $userDTO->name = 'Jane Doe';
    $userDTO->age = 25;
    
    $array = $userDTO->toArray();
    $json = $userDTO->toJson();
    
  5. DTO Factory Create DTOs from arrays or other DTOs:

    $data = ['name' => 'Alice', 'age' => 30];
    $userDTO = DTOManager::createDTO('App\DTO\UserDTO', $data);
    

Integration Tips

  1. Laravel Request Binding Bind DTOs to incoming requests:

    use Illuminate\Http\Request;
    use Solido\DTOManagement\Facades\DTOManager;
    
    public function store(Request $request)
    {
        $dto = DTOManager::bindDTO('App\DTO\UserDTO', $request->all());
        // Process $dto
    }
    
  2. API Responses Return DTOs as API responses:

    return response()->json(DTOManager::getDTO('App\DTO\UserDTO', $data));
    
  3. Event Dispatching Dispatch events when DTOs are created or updated:

    DTOManager::getDTO('App\DTO\UserDTO', $data)->dispatchEvents();
    
  4. Testing Mock DTOs in tests:

    $mockDTO = Mockery::mock('overload:' . App\DTO\UserDTO::class);
    $mockDTO->shouldReceive('name')->andReturn('Test User');
    

Gotchas and Tips

Pitfalls

  1. DTO Registration

    • Forgetting to register DTOs in config/dto-management.php will throw DTONotFoundException.
    • Fix: Ensure all DTOs are listed under the dto key.
  2. Version Mismatches

    • Accessing fields that don’t exist in a DTO version will trigger UndefinedPropertyException.
    • Fix: Use DTOManager::supportsVersion() to check compatibility:
      if (DTOManager::supportsVersion('App\DTO\UserDTO', '2.0', 'email')) {
          $dto->email = 'test@example.com';
      }
      
  3. Circular References

    • DTOs referencing each other (e.g., UserDTO has AddressDTO, which has UserDTO) can cause infinite loops during serialization.
    • Fix: Use DTOManager::setCircularReferenceHandler():
      DTOManager::setCircularReferenceHandler(function ($dto) {
          return $dto->id; // Return a simple identifier
      });
      
  4. Enhancer Conflicts

    • Multiple enhancers for the same DTO may override each other unpredictably.
    • Fix: Order enhancers in config/dto-management.php or use namespaced enhancer classes.
  5. Validation Overrides

    • Custom rules() methods in DTOs are merged with config-based rules, which can lead to unexpected behavior.
    • Fix: Explicitly define validation logic in one place (either in DTO or config).

Debugging Tips

  1. Enable Debug Mode Set 'debug' => true in config/dto-management.php to log DTO operations.

  2. DTO Dumping Use DTOManager::dumpDTO() to inspect DTO structure:

    DTOManager::dumpDTO('App\DTO\UserDTO', '2.0');
    
  3. Event Listening Listen for DTO events to debug lifecycle:

    DTOManager::listen('dto.created', function ($dto) {
        \Log::debug('DTO created:', $dto->toArray());
    });
    

Extension Points

  1. Custom DTO Resolvers Override how DTOs are resolved by binding to dto.resolved event:

    DTOManager::listen('dto.resolved', function ($dto, $version) {
        if ($version === '2.0') {
            $dto->email = 'default@example.com';
        }
    });
    
  2. Dynamic DTO Generation Use DTOManager::generateDTO() to create DTOs from runtime definitions:

    $dynamicDTO = DTOManager::generateDTO(
        'DynamicUserDTO',
        ['name' => 'string', 'age' => 'integer'],
        '1.0'
    );
    
  3. DTO Middleware Apply middleware to DTO operations:

    DTOManager::extend('App\DTO\UserDTO', function ($dto) {
        $dto->setMiddleware(function ($dto) {
            // Pre-process DTO
        });
    });
    
  4. Custom Serializers Replace default serialization with a custom strategy:

    DTOManager::setSerializer(function ($dto) {
        return json_encode($dto->toArray(), JSON_PRETTY_PRINT);
    });
    

Config Quirks

  1. Caching DTO definitions are cached by default. Clear cache after changes:

    php artisan cache:clear
    
  2. Autoloading Ensure DTO classes are autoloaded. Add them to composer.json:

    "autoload": {
        "psr-4": {
            "App\\DTO\\": "app/DTO/"
        }
    }
    
  3. Namespace Conflicts Avoid naming DTOs with reserved words (e.g., DTO, Manager). Use explicit namespaces.

  4. Environment-Specific Config Override DTO versions per environment:

    'dto' => env('DTO_ENV', [
        'App\DTO\UserDTO' => ['version' => '1.0'],
    ]),
    
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