Fun with structs

PHP 7.0 introduced great additions to it’s object model: type declarations and return type declarations. I use these features extensively and could never look back. It makes PHP code much more readable, and much more predictable.

There is still one gray area in PHP’s object model: typed properties. While we wait patiently for PHP 7.4 to implement typed properties, I felt like having fun trying to implement this language feature on my own.

This gave birth to the Structure PHP Package.

Installation

Install the Angle\Structure package via Composer:

composer require angle/structure

You can find the Structure package on Github and Packagist.

Writing our 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;
use Carbon\Carbon;

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

Mission accomplished!

If the struct isn’t compatible with the definition, PHP will throw an InvalidArgumentException exception.

This is exactly what we expect from structs: to let us know when our data structure is compromised, so we can write more robust code.

Published by Ben Villiere

Software Developer since 2007. I enjoy solving complex problems with efficient code. My mission is to help people improve their professional life by automating mundane tasks. This blog is my technical journal where I write about my work.

Follow me on: | |