angle/structure

This package is not installable via Composer 1.x, please make sure you upgrade to Composer 2+. Read more about our Composer 1.x deprecation policy.

Bring structs to PHP

v1.0.0 2019-02-04 18:46 UTC

This package is auto-updated.

Last update: 2021-05-29 01:22:06 UTC


README

Motivation

While we wait for typed properties to be implemented within PHP classes, let's have fun finding ways to implement this language feature on our own!

Installation

Install the Angle\Structure package via Composer:

composer require angle/structure

Your First Struct

Structs are php classes that make the use of the Structure trait. The trait will take over the class constructor, so make shure you use it only for strong typing properties (which structs are for basically).

<?php

namespace App\Structs;

use Angle\Structure\Structure;
use Carbon\Carbon;

class CarStruct
{
    use Structure;

    public $id = 0;
    public $model = '';
    public $mark = '';
    public $range = 0;
    public $power = 0.0;
    public $createdAt = Carbon::class;
}

To create the struct, simply instantiate a new object with an array of properties:

<?php

use App\Structs\CarStruct;

$car = new CarStruct([
    'id' => 12,
    'model' => 'Model S',
    'mark' => 'Tesla',
    'range' => 315,
    'power' => 560,
    'createdAt' => Carbon::now(),
]);

If any of the parameters are not of expected value, the constructor will throw an InvalidArgumentException error.

Licence

MIT

Copyright © 2019 Angle Software