anglesoft / structure

πŸ› Bring structs to PHP.

Home Page:https://angle.software/fun-with-structs/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Structure

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

About

πŸ› Bring structs to PHP.

https://angle.software/fun-with-structs/

License:MIT License


Languages

Language:PHP 100.0%