Files
php-react-protocol/doc/recipes.md
Christopher Vagnetoft 62a1167055 Initial commit
2026-04-02 22:29:35 +02:00

48 lines
1.4 KiB
Markdown

# Recipes
These are some suggestions and ideas for when building your own protocols using the
various protocol classes.
## Marshalling objects
You can use the beforePackCb and afterUnpackCb to serialize and unserialize parameters
as desired. Consider the security implications of this before you do anything stupid
though, as a spoofed frame could have unexpected consequences when unserialized.
```php
$proto = new JsonProtocol(
beforePackCb: function (array $frame): array {
$frame['obj'] = serialize($frame['obj']);
return $frame;
},
afterUnpackCb: function (array $frame): array {
$frame['obj'] = unserialize($frame['obj]);
return $frame;
},
);
```
## Building line-based messages
By using the `beforePackCb` callback, you can take messages in a structured format
and return them as a list for line-based protocols. You can do the same in reverse
with the `afterUnpackCb` callback.
```php
$proto = new LineProtocol(
beforePackCb: function (array $frame): array {
switch ($frame['cmd']) {
case 'search':
return [ "search", $frame['query'] ];
// ..
}
},
afterUnpackCb: function (array $frame): array {
switch ($frame[0]) {
case 'search':
return [ 'cmd' => $frame[0], 'query' => $frame[1] ];
// ..
}
}
)
```