Skip to content

Instantly share code, notes, and snippets.

<?php
/**
* Use spy when we want to be sure that the authorize method was called
* Warning: the more we spy, the tighter we couple our tests to the implementation of our system which leads to fragile tests
*/
class AcceptingAuthorizerSpy extends Authorizer {
$authorize_was_called = false;
public function authorize() {
<?php
/**
* Stub example: We will use this stub whenenver we need to test a system that requires a logged in user
*/
class AcceptingAuthorizerStub implements Authorizer {
public function authorize($username, $password) {
// always return true
return $true;
}
<?php
require_once "DummyAuthorizer.php";
require_once "System.php";
function test_system_has_no_loggedin_users() {
/*
* In this test I want to test loginCount() method and we don't need to provide any real authorizer to create the system object
* So we are passing a DummyAuthorizer whose authorize method would never be called from this test
*/
<?php
require_once "AuthorizerInterface.php";
class System {
public function __construct(AuthorizerInterface $authorizer) {
$this->authorizer = $authorizer;
}
public function loginCount() {
<?php
require_once "AuthorizerInterface.php";
/**
* Example of Test doubles, informally its being called as Mock (but not a real mock)
*/
class Authorizer implements AuthorizerInterface {
public function authorize($username, $password) {
// it implements actual authorization logic
<?php
require_once "AuthorizerInterface.php";
/**
* Example of Test doubles, informally its being called as Mock (but not a real mock)
*/
class DummyAuthorizer implements AuthorizerInterface {
public function authorize($username, $password) {
return null;
@shaikhul
shaikhul / AuthorizerInterface.php
Last active January 17, 2017 20:58
AuthorizerInterface
<?php
interface AuthorizerInterface {
public function authorize($username, $password);
}
@shaikhul
shaikhul / anonymous_function_currying.php
Created October 2, 2016 02:32
anonymous_function_currying.php
<?php
// define a curry function
$make_adder = function ($num1) {
return function ($num2) use ($num1) {
return $num1 + $num2;
};
};
$five_adder = $make_adder(5);
@shaikhul
shaikhul / annonymous_function_as_argument.php
Created October 2, 2016 02:30
annonymous_function_as_argument.php
<?php
// define a function that accepts a callable
function decorate(callable $func) {
return "<p>" . $func() . "</p>";
}
// execute decorate by passing an anonymous function
$result = decorate(function () {
return "Hello World!";
@shaikhul
shaikhul / lambda_function.php
Last active October 2, 2016 02:49
lamda_function.md
<?php
// create a lamda function by assigning an anonymous function to a variable
$greet = function ($name) {
return "Hello {$name}";
};
// it will print Hello World
echo $greet("World") . PHP_EOL;