Skip to content

Commit 18c9152

Browse files
committed
feat: adds afterConstruct overload method
1 parent 8e11e7b commit 18c9152

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

src/Models/Model.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff 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
/**
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
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+
}

tests/wpunit/ModelTest.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use StellarWP\Models\Tests\ModelsTestCase;
66
use StellarWP\Models\Tests\MockModel;
7+
use StellarWP\Models\Tests\MockModelWithAfterConstruct;
78
use 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
*

0 commit comments

Comments
 (0)