Skip to content

Instantly share code, notes, and snippets.

@NeilMasters
Last active March 31, 2023 07:59
Show Gist options
  • Save NeilMasters/2018c4f072901755b768306cf0a81d84 to your computer and use it in GitHub Desktop.
Save NeilMasters/2018c4f072901755b768306cf0a81d84 to your computer and use it in GitHub Desktop.
example trait doing heavy lifting in 8.2
<?php
trait Serialize {
public function jsonSerialize(): array
{
$array = [];
foreach (get_object_vars($this) as $var => $value) {
if ($value instanceof \JsonSerializable) {
$array[$var] = $this->$var->jsonSerializeToArray();
} else {
$array[$var] = $this->$var;
}
}
return $array;
}
}
abstract class IdOnly implements \JsonSerializable {
use Serialize;
public function __construct(public int $id) {}
}
class AcademicUnit extends IdOnly {}
class Student extends IdOnly {}
class EnrollStudentPhp8 implements \JsonSerializable
{
use Serialize;
public function __construct(
public AcademicUnit $academicUnit,
public Student $studentId,
public string | null $startDate = null,
public string | null $endDate = null,
public bool $enrollParents = false
) { }
}
$enroll = new EnrollStudentPhp8(
academicUnit: new AcademicUnit(1),
studentId: new Student(1)
);
var_dump($enroll->jsonSerialize());
@NeilMasters
Copy link
Author

Example code of a trait that can be stacked onto any class that iterates class params and adds them to a list. I agree It is a slight perversion but for its ability to cut down on boiler plate code especially in boring models, messages etc I think forgivable.

array(5) {
  ["academicUnit"]=> array(1) {
    ["id"]=> int(1)
  }
  ["studentId"]=> array(1) {
    ["id"]=> int(1)
  }
  ["startDate"]=> NULL
  ["endDate"]=> NULL
  ["enrollParents"]=> bool(false)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment