Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

Inject interface and not concrete class

class DB implements DBInterface
{
    // A bunch of methods fetching from real DB
}

class MockDB implements DBInterface
{
    // Has the same (interface) methods but returns some fixed data for testing.
}

class Posts
{
    public function __construct(DBInterface $db)
    {
        $this->db = $db;
    }

    public function get()
    {
        $this->db->query("....");
    }
}

$posts = new Posts(new DB);
$data  = $posts->get(); // This fetches from the real db

// And for testing
$posts = new Posts(new MockDB);
$data  = posts->get(); // Fetches from the mock DB instead
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #Inject #interface #concrete #class
ADD COMMENT
Topic
Name
9+4 =