PHP Backend Application(2)Logging Config IOC and Unit Test

32 篇文章 0 订阅
PHP Backend Application(2)Logging Config IOC and Unit Test

1 Configuration and Unit Test
I create file like config-stage.ini or config-local.ini.

The base class ConfigUtil.php will handle the config things for me.
<?php

namespace JobConsumerPHP;

class ConfigUtil
{

protected $config = null;

public function __construct()
{
$runningEnv = getenv('RUNNING_ENV');
if(empty($runningEnv))
{
$runningEnv = "local";
}
$this->config = parse_ini_file("src/config-${runningEnv}.ini");
}

public function getConfig(){
return $this->config;
}

}

?>

The UNIT Test class will be like this ConfigUtilTest.php
<?php

use \JobConsumerPHP\IOCUtil;

class ConfigUtilTest extends PHPUnit_Framework_TestCase
{

protected $config;

protected function setUp()
{
$ioc = new IOCUtil();
$this->config = $ioc->getService("config");
}

public function testDummy()
{
$this->assertTrue(true);
}

public function testGetConfig()
{
$this->assertNotEmpty($this->config);
$this->assertNotEmpty($this->config['redisHost']);
}
}

?>

We can run the single unit test file like this
>phpunit --bootstrap vendor/autoload.php tests/JobConsumerPHP/LoggerUtilTest

Or with the help of file phpunit.xml under the root directory
<phpunit bootstrap="vendor/autoload.php">
<testsuites>
<testsuite name="unitsuite">
<directory>tests</directory>
</testsuite>
</testsuites>
</phpunit>

We can directly run the command to run all the test suite
>phpunit

Our source codes will be auto load by the composer configuration in composer.json
{
"autoload" : {
"psr-0": {
"JobConsumerPHP": "src/"
}
},
"require": {
"aws/aws-sdk-php": "3.0.6",
"predis/predis": "1.0.1",
"katzgrau/klogger": "dev-master",
"pimple/pimple": "3.0"
},
"require-dev": {
"phpunit/phpunit": "5.1.*",
"phpunit/dbunit": ">=1.2",
"phpunit/php-invoker": "*"
}
}

2 Logging in PHP
Here is how the logging works in LoggerUtil.php
<?php

namespace JobConsumerPHP;

require 'vendor/autoload.php';

use \Psr\Log\LogLevel;
use \Katzgrau\KLogger\Logger;

class LoggerUtil
{
protected $logger = null;

public function __construct($ioc)
{
$this->logger = new Logger('logs');

$this->logger->setLogLevelThreshold(LogLevel::DEBUG);
}

public function getLogger(){
return $this->logger;
}
}

?>

3 IOC Container
This IOCUtil.php will help me to load all the PHP classes and features.
<?php

namespace JobConsumerPHP;

require 'vendor/autoload.php';

use \Pimple\Container;
use \JobConsumerPHP\ConfigUtil;
use \JobConsumerPHP\LoggerUtil;
use \JobConsumerPHP\RedisClient;

class IOCUtil
{

protected $ioc = null;

public function __construct()
{
$this->ioc = new Container();

//init config
$this->ioc["config"] = function ($c)
{
$configUtil = new ConfigUtil();
return $configUtil->getConfig();
};
//init logger
$this->ioc["logger"] = function ($c)
{
$loggerUtil = new LoggerUtil($this);
return $loggerUtil->getLogger();
};
//init redis client
$this->ioc["redisClient"] = function ($c)
{
$redisClient = new RedisClient($this);
return $redisClient;
};
}

public function getService($name)
{
return $this->ioc[$name];
}

}

?>

Here is how the RedisClient.php get the dependencies from IOC container
<?php

namespace JobConsumerPHP;

require 'vendor/autoload.php';
\Predis\Autoloader::register();

use \Predis\Client;

class RedisClient
{

protected $client = null;

public function __construct($ioc){

$logger = $ioc->getService("logger");
$config = $ioc->getService("config");

$logger->info("==============Redis config start ==============");
$logger->info("redisHost = " . $config['redisHost']);
$logger->info("redisPort = " . $config['redisPort']);
$logger->info("===============================================");

try {
$this->client = new Client(array(
"scheme" => "tcp",
"host" => $config["redisHost"],
"port" => $config["redisPort"]
));
$logger->debug("Successfully connected to Redis");
} catch (Exception $e) {
$logger->error("Couldn't connected to Redis");
$logger->error($e->getMessage());
}
}

public function exist($key)
{
$result = $this->client->exists($key);
return $result;
}

/**
*
*/
public function set($key, $value)
{
$result = $this->client->set($key, $value);
return $result;
}

public function get($key)
{
$result = $this->client->get($key);
return $result;
}

public function del($key)
{
$result = $this->client->del($key);
return $result;
}
}

?>

Here is how the unit test load all the classes, RedisClientTest.php
<?php

use \JobConsumerPHP\IOCUtil;

class RedisClientTest extends PHPUnit_Framework_TestCase
{

protected $redisClient;

protected function setUp()
{
$ioc = new IOCUtil();
$this->redisClient = $ioc->getService("redisClient");
}

public function testDummy()
{
$this->assertTrue(true);
}

public function testRedisClient()
{
$this->assertNotEmpty($this->redisClient);
}

public function testCRUD()
{
//set value
$this->redisClient->set("key1","value1");

//check exist
$result1 = $this->redisClient->exist("key1");
$this->assertEquals($result1, true);

//get
$result2 = $this->redisClient->get("key1");
$this->assertEquals($result2, "value1");
}
}

?>

Here is how the normal PHP Backend Script load and use IOC in RawJobApp.php
<?php

require_once 'JobConsumerPHP/IOCUtil.php';

use \JobConsumerPHP\IOCUtil;

$ioc = new IOCUtil();

$redisClient = $ioc->getService("redisClient");

$redisClient->set("key1", "lujin");

?>

References:
PHPUnit
https://phpunit.de/manual/current/en/fixtures.html

http://sillycat.iteye.com/blog/2302288

IOC Container
https://github.com/silexphp/Pimple

http://pimple.sensiolabs.org/

KLogger
https://github.com/katzgrau/KLogger

PHP Standard
http://www.php-fig.org/psr/psr-0/

http://www.php-fig.org/psr/psr-1/

http://www.php-fig.org/psr/psr-2/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值