Skip to content

Add support for plain objects with promoted properties in message queue communication #36660

@speller

Description

@speller

Description

Add support for plain objects with promoted properties in message queue communication.

PHP 8 allows to use the following immutable data objects with promoted properties:

class CacheFlushMessage
{
    public function __construct(
        public readonly CacheFlushMessageType $messageType,
        public readonly string $cacheType,
        public readonly AppMode $source,
    ) {
    }
}

This allows to keep the user code clean by using modern language features with less code doing the same as old-styled code with regular constructor properties and getter methods.

But I can not add this object to the communication.xml file as-is:

    <topic name="test" request="CacheFlushMessage"/>

The resulting emitted message body will be empty.

The workaround is to use a custom encoder and markup such classes somehow. For example, use a marker interface:

interface PlainJsonDataInterface
{
}

class CacheFlushMessage implements PlainJsonDataInterface
{
    public function __construct(
        public readonly CacheFlushMessageType $messageType,
        public readonly string $cacheType,
        public readonly AppMode $source,
    ) {
    }
}

class PlainJsonDataProcessor
{
    public function execute(
        PlainJsonDataInterface $dataObject,
        array $result
    ): array {
        return array_merge($result, json_decode(json_encode($dataObject), 'true'));
    }
}
    <type name="Magento\Framework\Reflection\DataObjectProcessor">
        <arguments>
            <argument name="processors" xsi:type="array">
                <item name="PlainJsonDataInterface" xsi:type="object">PlainJsonDataProcessor</item>
            </argument>
        </arguments>
    </type>

Expected behavior

I'm able to use a data class with promoted properties without workarounds.

Benefits

Better user code quality

Additional information

No response

Release note

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    Ready for Grooming

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions