-
Notifications
You must be signed in to change notification settings - Fork 44
Matchers
Matchers are used to compare the return values of controls, to that of our trials. Ideally, we want our trials to replicate the functionality of our control in a much more efficient way. To ensure that we don't break our application, the return values must match.
By default, Scientist uses an instance of Scientist\Matchers\StandardMatcher
to perform matching operations. Internally, it simply performs a strict ===
comparison on the return values of the control and the trial.
If you're using more complex objects, a simple strict ===
comparison might not be enough. Fortunately, Scientist offers the ability to create custom matchers that we can use in our experiments.
To create a custom matcher, we must extend the Scientist\Matchers\Matcher
abstract class. Here's an example.
namespace MyApp;
use Scientist\Matchers\Matcher;
/**
* Class StandardMatcher
*
* @package \Scientist\Matchers
*/
class MyMatcher implements Matcher
{
/**
* Determine whether two values match.
*
* @param mixed $control
* @param mixed $trial
*
* @return boolean
*/
public function match($control, $trial)
{
// Perform matching evaluation here.
}
}
Here, we've created a new matcher, for our own evil purposes.
The match()
method, receives the value from the control, and the value from a trial. It's up to us to determine whether or not they match. We must implement the code that will return a boolean value.
Returning a true
boolean value will indicate a match, and experiments utilising this matcher will indicate a match within their result report. A return value of false
will indicate that a match did not occur.
Let's say that our application has a User
class. This class contains a property for a users name, alongside a number of other properties and methods. A direct comparison will likely not be desired, as the object is fairly complex.
Instead, we only wish to compare the name of the user. Let's define a matcher to accomplish this task.
namespace MyApp;
use Scientist\Matchers\Matcher;
/**
* Class StandardMatcher
*
* @package \Scientist\Matchers
*/
class UserMatcher implements Matcher
{
/**
* Determine whether two values match.
*
* @param mixed $control
* @param mixed $trial
*
* @return boolean
*/
public function match($control, $trial)
{
return $control->name == $trial->name;
}
}
In our new matcher, we're checking to see if the user names match.
We'll need to apply this matcher to our experiment before we can use it. Don't worry. It's simple!
$experiment = (new Scientist\Laboratory)
->experiment('experiment title')
->control($controlCallback)
->trial('trial name', $trialCallback)
->matcher(new \\MyApp\\UserMatcher);
$value = $experiment->run();
Simply use the matcher()
method on the experiment to attach our custom matcher. It will then replace the StandardMatcher
for this experiment. Huzzah!