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

Php Object Converter Bundle Laravel Package

baudev/php-object-converter-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require baudev/php-object-converter-bundle
    

    For Symfony Flex projects, the bundle auto-enables. For manual setups, add it to AppKernel.php.

  2. First Use Case: Convert a PHP class (e.g., User) to another language (e.g., JavaScript). Run:

    bin/console converter:generate converter User src/Converter/Output
    
    • converter: The command name (default in the bundle).
    • User: Your source PHP class (must be autoloadable).
    • src/Converter/Output: Target directory for generated files.
  3. Where to Look First:

    • Check config/packages/baudev_php_object_converter.yaml for default configurations (e.g., supported languages, naming conventions).
    • Review generated files in Output/ to understand the output structure.
    • Consult the Symfony Console documentation for command customization.

Implementation Patterns

Core Workflows

  1. Class-to-Language Conversion:

    • Use the converter:generate command to serialize PHP classes into target languages (e.g., TypeScript, Java, C#).
    • Example:
      bin/console converter:generate converter User src/Converter/Output --language=typescript
      
    • Supported languages are defined in the bundle’s configuration (extend via config/packages/baudev_php_object_converter.yaml).
  2. Integration with Laravel (Symfony-Compatible):

    • Service Registration: Bind the converter service to Laravel’s container in config/app.php:
      'bindings' => [
          Baudev\PHPObjectConverterBundle\Converter\ConverterInterface::class => Baudev\PHPObjectConverterBundle\Converter\Converter::class,
      ],
      
    • Manual Conversion: Inject the converter service into a Laravel service class:
      use Baudev\PHPObjectConverterBundle\Converter\ConverterInterface;
      
      class MyService {
          public function __construct(private ConverterInterface $converter) {}
      
          public function convertUserToJson(User $user) {
              $converted = $this->converter->convert($user, 'json');
              return json_decode($converted, true);
          }
      }
      
  3. Customizing Output:

    • Override default templates by extending the bundle’s Twig environment (if supported) or by modifying the converter:generate command’s arguments.
    • Example: Force a specific naming convention:
      bin/console converter:generate converter User src/Converter/Output --class-name-prefix="Dto_"
      
  4. Event-Driven Conversion:

    • Listen for class generation events (if the bundle supports them) to post-process outputs. Example in Laravel:
      use Symfony\Component\Console\Event\ConsoleTerminateEvent;
      use Symfony\Component\EventDispatcher\EventSubscriberInterface;
      
      class ConversionSubscriber implements EventSubscriberInterface {
          public static function getSubscribedEvents() {
              return [
                  'console.terminate' => 'onConversionTerminate',
              ];
          }
      
          public function onConversionTerminate(ConsoleTerminateEvent $event) {
              if ($event->getCommand()->getName() === 'converter:generate') {
                  // Post-process generated files (e.g., minify JS, lint TS).
              }
          }
      }
      
  5. API Response Conversion:

    • Convert Laravel Eloquent models to API responses in other languages (e.g., GraphQL schemas or mobile SDKs):
      $user = User::find(1);
      $graphqlType = $this->converter->convert($user, 'graphql');
      

Gotchas and Tips

Pitfalls

  1. Deprecated Bundle:

    • Last release in 2019; test thoroughly for compatibility with modern PHP (8.0+) and Symfony/Laravel versions.
    • May lack support for newer PHP features (e.g., enums, attributes, union types).
  2. Limited Language Support:

    • Only includes basic converters (e.g., JSON, XML, TypeScript). Custom languages require manual implementation or forking the bundle.
    • Example: To add Go, extend the Converter class and register it in the bundle’s configuration.
  3. Command Argument Sensitivity:

    • The converter:generate command is strict about class names and paths. Use fully qualified names (e.g., App\Models\User) to avoid autoloading issues.
    • Output directories must be writable; Laravel’s storage/ or app/ are safe choices.
  4. Circular References:

    • The bundle may fail silently on recursive class relationships (e.g., UserPost). Handle manually or pre-process data:
      $user = User::with('posts')->find(1);
      $this->converter->convert($user, 'json', ['maxDepth' => 1]);
      
  5. Configuration Overrides:

    • Custom configurations in config/packages/baudev_php_object_converter.yaml are merged, not replaced. Use !override for precedence:
      baudev_php_object_converter:
          languages:
              typescript: !override
                  template: 'custom_ts_template.twig'
      

Debugging Tips

  1. Dry Runs:

    • Use --dry-run (if supported) to preview changes without writing files:
      bin/console converter:generate converter User --dry-run
      
  2. Logging:

    • Enable Symfony’s debug mode (APP_DEBUG=true) to log conversion errors. Check var/log/dev.log in Laravel.
  3. Template Debugging:

    • If using Twig templates, enable Twig debugging in config/packages/twig.yaml:
      twig:
          debug: true
          strict_variables: true
      
  4. Fallback to Raw Conversion:

    • For unsupported types, fall back to json_encode or serialize:
      $raw = $this->converter->convert($user, 'json', ['fallback' => true]);
      

Extension Points

  1. Custom Converters:

    • Implement Baudev\PHPObjectConverterBundle\Converter\ConverterInterface for new languages. Example:
      class RustConverter implements ConverterInterface {
          public function convert($object, array $options = []): string {
              // Custom logic to convert PHP to Rust structs.
              return "pub struct User {\n    pub id: i32,\n}";
          }
      }
      
    • Register the converter in the bundle’s services:
      services:
          Baudev\PHPObjectConverterBundle\Converter\ConverterInterface:
              alias: 'app.rust_converter'
              public: true
      
  2. Pre/Post-Processing:

    • Use Laravel’s booted event to hook into the bundle’s lifecycle:
      use Baudev\PHPObjectConverterBundle\Event\ConversionEvent;
      
      public function boot() {
          event(new ConversionEvent($user, 'json'));
          // Trigger custom logic before/after conversion.
      }
      
  3. Testing:

    • Mock the converter in PHPUnit tests:
      $this->mock(Baudev\PHPObjectConverterBundle\Converter\ConverterInterface::class)
           ->shouldReceive('convert')
           ->once()
           ->andReturn('{"id":1}');
      
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope