-
Notifications
You must be signed in to change notification settings - Fork 0
Structure
Ryan Durham edited this page Nov 27, 2021
·
2 revisions
A structure (or 'struct') is a composite of primitive types that always takes the same form.
To define a struct, create a class that implements the StageRightLabs\PhpXdr\Interfaces\XdrStruct
interface. This interface has two methods:
-
toXdr(XDR &$xdr): void
: Use an XDR buffer to compose the data that makes up the structure. -
static newFromXdr(XDR &$xdr): static
: Read data from an XDR buffer and return a new instance of the class.
NB: unlike other composite type interfaces, this package cannot encode and decode the value of a struct automatically. Instead you must implement this in the methods described above. Both methods are given a reference to an XDR buffer from which you can read and write as needed.
For example:
use StageRightLabs\PhpXdr\XDR;
use StageRightLabs\PhpXdr\Interfaces\XdrStruct;
class HighScore implements XdrStruct
{
public function __construct(public int $score, public string $name)
{
$this->score = $score;
$this->name = $name;
}
public function toXdr(XDR &$xdr): void {
$xdr->write($this->score, XDR::INT);
$xdr->write($this->name, XDR::STRING);
}
public static function newFromXdr(XDR &$xdr): static
{
$score = $xdr->read(XDR::INT);
$name = $xdr->read(XDR::STRING);
return new static($score, $name);
}
}
To encode a struct:
use StageRightLabs\PhpXdr\XDR;
$highScore = new HighScore(score: 256, name: 'Hiro Protagonist');
$xdr = XDR::fresh()->write($highScore, XDR::STRUCT);
To decode a struct:
$highScore = $xdr->read(XDR::STRUCT, HighScore::class);
$highScore->score == 256; // true
$highScore->name == 'Hiro Protagonist'; // true