Last active
March 31, 2023 07:59
-
-
Save NeilMasters/2018c4f072901755b768306cf0a81d84 to your computer and use it in GitHub Desktop.
example trait doing heavy lifting in 8.2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.