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

Oxm Laravel Package

doctrine/oxm

Doctrine OXM (Object XML Mapper) maps PHP objects to XML documents and back using Doctrine-style metadata. Useful for XML serialization/deserialization in domain models, with mapping drivers and runtime tools to integrate XML workflows into applications.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require doctrine/oxm
    

    Ensure doctrine/orm is also installed (OXM relies on Doctrine ORM components):

    composer require doctrine/orm
    
  2. Basic Setup Configure OXM in config/doctrine.php (or create it if missing):

    'orm' => [
        'entity_managers' => [
            'default' => [
                'mappings' => [
                    'App\\Models' => [
                        'type' => 'xml',
                        'dir' => base_path('app/Models'),
                        'prefix' => 'App\\Models',
                        'is_bundle' => false,
                    ],
                ],
            ],
        ],
    ],
    
  3. First Use Case: Mapping a Model to XML Annotate a Laravel model with OXM attributes:

    use Doctrine\ORM\Mapping as ORM;
    use Doctrine\ODM\XMLMapping\Mapping\Driver\AnnotationDriver;
    
    /**
     * @ORM\Entity
     * @ORM\Table(name="users")
     * @ORM\XmlRoot(name="user")
     */
    class User extends Model
    {
        /**
         * @ORM\Id
         * @ORM\Column(type="integer")
         * @ORM\XmlId
         * @ORM\GeneratedValue
         */
        protected $id;
    
        /**
         * @ORM\Column(type="string")
         * @ORM\XmlElement
         */
        protected $name;
    }
    
  4. Generate XML Schema Use the CLI to generate XML schema from annotations:

    php artisan doctrine:schema:update --force
    

    Or manually generate XML mapping files:

    vendor/bin/doctrine-mapping-import --path=src/ --output-dir=config/doctrine/xml
    

Implementation Patterns

Workflows

  1. CRUD Operations with XML Use Doctrine's EntityManager to read/write XML:

    $em = Doctrine::em();
    $user = $em->find('App\Models\User', 1);
    $xml = $em->getXMLMapping()->getClassMetadata('App\Models\User')->getXMLSchema();
    
  2. Bulk XML Export/Import Iterate over collections and serialize to XML:

    $users = User::all();
    $xml = new \SimpleXMLElement('<users/>');
    foreach ($users as $user) {
        $userXml = $em->getXMLMapping()->getClassMetadata('App\Models\User')->getXMLSchema();
        $xml->addChild('user', $userXml->asXML());
    }
    
  3. Integration with Laravel Events Trigger XML export on model events (e.g., saved):

    User::saved(function ($user) {
        $xml = $user->toXml(); // Custom method to serialize
        Storage::put("users/{$user->id}.xml", $xml);
    });
    

Integration Tips

  • Hybrid ORM/ODM: Use OXM alongside Eloquent for models requiring XML serialization.
  • Custom Hydrators: Extend Doctrine\ODM\XMLMapping\Hydrator\ObjectHydrator for complex mappings.
  • API Responses: Serialize models to XML for legacy API endpoints:
    return response($user->toXml(), 200, ['Content-Type' => 'application/xml']);
    

Gotchas and Tips

Pitfalls

  1. Annotation vs. XML Mapping

    • OXM primarily uses annotations (@ORM\Xml*), but conflicts may arise with Doctrine ORM annotations. Ensure consistency:
      // Avoid mixing:
      @ORM\Column(type="string") // ORM
      @ORM\XmlElement(cdata=false) // OXM
      
  2. Circular References Bidirectional relationships (e.g., User <-> Role) may cause infinite XML loops. Use @ORM\XmlInverseJoinColumn or lazy-loading:

    /**
     * @ORM\ManyToMany(targetEntity="Role")
     * @ORM\XmlElement
     * @ORM\XmlInverseJoinColumn
     */
    private $roles;
    
  3. Namespace Collisions XML namespaces in generated schemas may clash. Explicitly define namespaces in annotations:

    @ORM\XmlRoot(namespace="http://example.com/ns")
    

Debugging

  • Schema Validation: Use vendor/bin/doctrine-mapping-import --validate to check for errors.
  • Logging: Enable Doctrine logging in config/doctrine.php:
    'logging' => true,
    'log_level' => \Doctrine\Common\Logging\LogLevel::DEBUG,
    
  • XML Output: Inspect raw XML with:
    $metadata = $em->getClassMetadata('App\Models\User');
    $xmlSchema = $metadata->getXMLSchema();
    file_put_contents('debug.xml', $xmlSchema->asXML());
    

Extension Points

  1. Custom Drivers Implement Doctrine\Common\Persistence\Mapping\Driver\MappingDriverInterface for non-annotation-based mappings (e.g., YAML).

  2. Event Subscribers Listen to onFlush or postPersist to modify XML output dynamically:

    $em->getEventManager()->addEventSubscriber(new class {
        public function postPersist(LifecycleEventArgs $args) {
            $entity = $args->getObject();
            if ($entity instanceof User) {
                $entity->setXmlAttribute('exported_at', now()->toAtomString());
            }
        }
    });
    
  3. Laravel Service Provider Bootstrap OXM in AppServiceProvider:

    public function boot() {
        $this->app->singleton('doctrine.em', function () {
            $config = config('doctrine.orm.entity_managers.default');
            $em = EntityManager::create($config['connection'], $config['mappings']);
            return $em;
        });
    }
    
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.
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
spatie/mailcoach-vapor