Skip to content
Snippets Groups Projects
Commit fba19ca4 authored by Thomas Flori's avatar Thomas Flori
Browse files

pushed to version 1.0.0

parent 87603090
No related branches found
No related tags found
No related merge requests found
Pipeline #193 passed with stage
# Changelog
## Version 1.1
* class requests have to be case sensitive to prevent return object instead of string
* added better examples
{
"name": "tflori/dependency-injector",
"version": "1.0.0",
"version": "1.1.0",
"description": "Easy and lightweight dependency injector",
"type": "library",
"keywords": [
......
......@@ -45,7 +45,14 @@ class DI {
} elseif (class_exists($name)) {
return $name;
$reflection = new \ReflectionClass($name);
if ($reflection->getName() === $name) {
self::$_instances[$name] = $name;
return self::$_instances[$name];
}
}
......
......@@ -140,8 +140,18 @@ class DependencyInjectorTest extends TestCase {
*/
public function testGet_returnsClassName() {
$result = DI::get(__CLASS__);
}
/**
* Test that a class name has to be case sensitive.
*/
public function testGet_classNameIsCaseSensitive() {
$this->expectException(DependencyInjector\Exception::class);
$this->expectExceptionMessage("Unknown dependency '" . strtolower(__CLASS__) . "'");
$result = DI::get(strtolower(__CLASS__));
$this->assertSame(__CLASS__, $result);
$this->assertNotSame(strtolower(__CLASS__), $result);
}
/**
......
<?php
use DependencyInjector\DI;
use PHPUnit\Framework\TestCase;
require_once __DIR__ . '/legacyCode.php';
class DataProviderTest extends TestCase {
/**
* @var DataProvider
*/
protected $dataProvider;
protected function setUp() {
// to mock the database during tests
DI::set('database', function() {
$mock = Mockery::mock('DatabaseObject');
$mock->shouldReceive('query')->andReturn([])->byDefault();
});
$this->dataProvider = new DataProvider;
parent::setUp();
}
public function tearDown() {
Mockery::close();
parent::tearDown();
}
public function testReturnsCached() {
$mock = Mockery::mock('memcache_class');
$mock->shouldReceive('get')->once()->with('SomeMemcacheKey')->andReturn('anyResult');
DI::set('memcache', $mock);
$result = $this->dataProvider->getSomeData();
self::assertSame('anyResult', $result);
}
public function testQueriesDatabase() {
$memcache = Mockery::mock('memcache_class');
$memcache->shouldReceive('get')->andReturn(null);
$memcache->shouldIgnoreMissing();
DI::set('memcache', $memcache);
$database = Mockery::mock(DatabaseObject::class);
$database->shouldReceive('query')
->once()->with("SELECT * FROM someDatabase.someTable")
->andReturn('fooBar');
DI::set('database', $database);
$result = $this->dataProvider->getSomeData();
self::assertSame('fooBar', $result);
}
}
<?php
use DependencyInjector\DI;
class DatabaseObject {
/**
* @var PDO
*/
private static $connection;
/**
* Execute a query and return the result set.
*
* @param string $sql
* @return array
* @throws Exception
*/
public function query($sql) {
$connection = self::getConnection();
$result = $connection->query($sql);
if (!$result) {
throw new Exception('SQL error');
}
return $result->fetchAll();
}
/**
* @return PDO
*/
private static function getConnection() {
if (!self::$connection) {
self::$connection = new PDO('mysql:host=localhost;dbname=anything');
}
return self::$connection;
}
}
// has to be added (maybe at config stage or bootstrap)
//DI::set('database', function() { return new DatabaseObject(); }, false);
<?php
use DependencyInjector\DI;
require_once __DIR__ . '/memcache.php';
class DataProvider {
public function getSomeData() {
$key = "SomeMemcacheKey";
// before it was untestable
// $cache = getMemcache();
/** @var Memcached $cache */
$cache = DI::get('memcache');
$results = $cache->get($key);
if (!$results) {
// before it was untestable
// $database = new DatabaseObject();
/** @var DatabaseObject $database */
$database = DI::get('database');
$sql = "SELECT * FROM someDatabase.someTable";
$results = $database->query($sql);
$cache->set($key, $results);
}
return $results;
}
}
<?php
// before
//function getMemcache() {
// static $memcache;
// if (!$memcache) {
// $memcache = new Memcached();
// $memcache->addServer('localhost', 11211);
// }
// return $memcache;
//}
// now
use DependencyInjector\DI;
DI::set('memcache', function() {
$memcache = new Memcached();
$memcache->addServer('localhost', 11211);
return $memcache;
});
<?php
use DependencyInjector\DI;
use PHPUnit\Framework\TestCase;
require_once __DIR__ . '/MySingleton.php';
require_once __DIR__ . '/legacyCode.php';
class MySingletonTest extends PHPUnit_Framework_TestCase {
public function testClassExists() {
self::assertTrue(class_exists('MySingleton'));
}
class MySingletonTest extends TestCase {
/**
* Test the default behaviour of your code.
*/
public function testGetAnObject() {
/** @var $mySingleton MySingleton */
$mySingleton = (DI::get(MySingleton::class))::getInstance();
// act
$result = getTheSingletonResult();
self::assertTrue($mySingleton instanceof MySingleton);
self::assertSame('defaultResult', $mySingleton->getResult());
//assert
self::assertSame('defaultResult', $result);
}
/**
......@@ -26,18 +24,31 @@ class MySingletonTest extends PHPUnit_Framework_TestCase {
public function testGetAMockObject() {
// prepare the mock
$mock = Mockery::mock(MySingleton::class);
$mock->shouldIgnoreMissing();
$mock->shouldReceive('getInstance')->andReturnSelf();
DI::set(MySingleton::class, $mock);
// assign
$mock->shouldReceive('getResult')->andReturn('differentResult');
$mock->shouldReceive('getResult')->once()->andReturn('differentResult');
// act
$result = getTheSingletonResult();
// assert
self::assertSame('differentResult', $result);
}
public function testGetResultFromMock() {
// assign
$mock = Mockery::mock(MySingleton::class);
$mock->shouldReceive('getResult')->once()->andReturn('anotherResult');
DI::set('mySingleton', $mock);
// act like your would usually act in your app
/** @var $mySingleton MySingleton */
$mySingleton = (DI::get(MySingleton::class))::getInstance();
// act
$singletonUser = new SingletonUser();
$result = $singletonUser->getResult();
// assert different result
self::assertTrue($mySingleton instanceof MySingleton);
self::assertSame('differentResult', $mySingleton->getResult());
// assert
self::assertSame('anotherResult', $result);
}
}
<?php
use DependencyInjector\DI;
require_once __DIR__ . '/MySingleton.php';
/**
* It's just a simple function that is using MySingleton static method.
*
* @return string
*/
function getTheSingletonResult() {
// before it was untestable
// $singleton = MySingleton::getInstance();
/** @var $singleton MySingleton */
$singleton = (DI::get(MySingleton::class))::getInstance();
return $singleton->getResult();
}
/**
* Class SingletonUser
*
* Uses the singleton to get a result.
*/
class SingletonUser {
/**
* This method shows a second way how to rewrite existing code to be testable. But remember that you have to
* set up the dependency before using it (for example in bootstrap).
*
* Example:
* DI::set('mySingleton', function() { return MySingleton::getInstance(); });
*
* @return mixed
*/
public function getResult() {
// before it was untestable
// return MySingleton::getInstance()->getResult();
return DI::get('mySingleton')->getResult();
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment