File tree Expand file tree Collapse file tree 3 files changed +45
-0
lines changed
Expand file tree Collapse file tree 3 files changed +45
-0
lines changed Original file line number Diff line number Diff line change @@ -59,6 +59,18 @@ final public function __construct( array $attributes = [] ) {
5959 $ this ->fill ( array_merge ( static ::getPropertyDefaults (), $ attributes ) );
6060
6161 $ this ->syncOriginal ();
62+
63+ $ this ->afterConstruct ();
64+ }
65+
66+ /**
67+ * This method is meant to be overridden by the model to perform actions after the model is constructed.
68+ *
69+ * @since 2.0.0
70+ */
71+ protected function afterConstruct () {
72+ // This method is meant to be overridden by the model to perform actions after the model is constructed.
73+ return ;
6274 }
6375
6476 /**
Original file line number Diff line number Diff line change 1+ <?php
2+
3+ namespace StellarWP \Models \Tests ;
4+
5+ use StellarWP \Models \Model ;
6+
7+ class MockModelWithAfterConstruct extends Model {
8+ protected static $ properties = [
9+ 'id ' => 'int ' ,
10+ 'name ' => 'string ' ,
11+ ];
12+
13+ public bool $ afterConstructCalled = false ;
14+ public array $ constructedAttributes = [];
15+
16+ protected function afterConstruct () {
17+ $ this ->afterConstructCalled = true ;
18+ $ this ->constructedAttributes = $ this ->toArray ();
19+ }
20+ }
Original file line number Diff line number Diff line change 44
55use StellarWP \Models \Tests \ModelsTestCase ;
66use StellarWP \Models \Tests \MockModel ;
7+ use StellarWP \Models \Tests \MockModelWithAfterConstruct ;
78use StellarWP \Models \Tests \MockModelWithRelationship ;
89
910/**
@@ -331,6 +332,18 @@ public function testFromDataShouldThrowExceptionForNonPrimitiveTypes(): void {
331332 ] );
332333 }
333334
335+ /**
336+ * @since 2.0.0
337+ *
338+ * @return void
339+ */
340+ public function testOnConstructedIsCalledDuringConstruction () {
341+ $ model = new MockModelWithAfterConstruct ( [ 'id ' => 1 , 'name ' => 'Test ' ] );
342+
343+ $ this ->assertTrue ( $ model ->afterConstructCalled );
344+ $ this ->assertEquals ( [ 'id ' => 1 , 'name ' => 'Test ' ], $ model ->constructedAttributes );
345+ }
346+
334347 /**
335348 * @since 1.0.0
336349 *
You can’t perform that action at this time.
0 commit comments