Skip to content

Instantly share code, notes, and snippets.

@inxilpro
Created May 26, 2022 20:44
Show Gist options
  • Save inxilpro/45a78ff540df1832b0975f58467a3324 to your computer and use it in GitHub Desktop.
Save inxilpro/45a78ff540df1832b0975f58467a3324 to your computer and use it in GitHub Desktop.
<?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()
{
// ...
}
}
<?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
}
<?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