Created
May 26, 2022 20:44
-
-
Save inxilpro/45a78ff540df1832b0975f58467a3324 to your computer and use it in GitHub Desktop.
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 | |
// Imagine you have a class that memoizes some data statically (let's assume | |
// the data is computationally expensive to load) | |
class ExpensiveDataHelper | |
{ | |
protected static $expensive_data = null; | |
public function getExpensiveData() | |
{ | |
return static::$expensive_data ??= $this->loadExpensiveData(); | |
} | |
protected function loadExpensiveData() | |
{ | |
// ... | |
} | |
} |
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 | |
// Somewhere in a test, you create data that the helper will load and | |
// then call some code that uses the helper | |
public function test_something_that_uses_expensive_data() | |
{ | |
Data::factory()->someState()->create(); | |
$data = ExpensiveDataHelper::getExpensiveData(); | |
// Perform assertions on data | |
} |
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 | |
// Now in another test, you create *different* test data and run your tests. | |
// If the data has already been memoized, your test will fail because | |
// it's not truly isolated from your other tests | |
public function test_something_that_uses_expensive_data() | |
{ | |
Data::factory()->someOtherState()->create(); | |
$data = ExpensiveDataHelper::getExpensiveData(); | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment