`
sillycat
  • 浏览: 2539163 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

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

 
阅读更多
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/
分享到:
评论

相关推荐

    Full-Stack Vue.js 2 and Laravel 5 Bring the frontend and backend together epub

    Full-Stack Vue.js 2 and Laravel 5 Bring the frontend and backend together with Vue, Vuex, and Laravel 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 查看此书详细信息请在美国亚马逊官网...

    Backend_Application

    在项目"Backend_Application-main"中,我们可以期待找到与上述知识点相关的源代码、配置文件和资源。通过阅读和分析这些内容,可以深入理解一个基于Java的后端应用是如何设计和实现的。开发者可能还使用了Maven或...

    开源项目-1backend-1backend.zip

    1backend 是一个开源项目,它采用了先进的技术栈,包括 Go 语言和 Angular 2(现称为 Angular),构建了一个平台即服务(PaaS)系统。这个项目的目标是提供一个高效、可扩展且易于使用的云基础设施,使得开发者能够...

    CornPrincess#Backend_Notes#深入浅出Ioc1

    引入Ioc: Inversion of Control 中文名即控制反转,这是一种设计思想,有点类似于设计模式,并不是一门具体的技术。其核心为将你设计好的对象由

    hbbtv-logging-backend:这是一个简单的日志后端

    HbbTV 记录器此记录器是 Hbbtv 库记录功能的展示科技基于: - v1.xx - 参见(v1.2.1 勘误表 1) - v2.3.0 - v2.3.0安装在您选择的 apache 服务器上运行,例如 xampp(必须安装 PHP) 确保重写规则允许从 index.php ...

    Go-go-logging一个简化的Go日志记录组件

    开发者可以根据需求编写自定义的backend和formatter,扩展`go-logging`的功能。例如,可以创建一个将日志发送到云日志服务的backend。 9. **性能优化** 考虑到性能,`go-logging`在日志级别过滤方面做了优化,...

    Tkinter GUI Application Development HOTSHOT(PACKT,2013)

    building real-world, productive and fun applications like text editor, drum machine, game of chess, media player, drawing application and many more. Each subsequent project builds on the skills ...

    Mastering The Faster Web with PHP, MySQL, and JavaScript 1st pdf

    Ensure seamless implementation of a JavaScript & HTML 5 CSS based frontend and PHP based backend. Learn about problem identification, best strategies, and UI design patterns as well to build a clean, ...

    PHP Reactive Programming

    The book will then focus on writing extendable RxPHP code by developing a code testing tool and also cover Using RxPHP on both the server and client side of the application. With a concluding chapter...

    backend_test

    "backend_test"这个项目很可能是一个用于测试后端技术的实例,可能包括了服务器搭建、API接口设计以及数据库操作等内容。由于标签中提到了"JavaScript",我们可以推断这个项目可能是使用JavaScript作为主要的后端...

    Laravel开发-laravel-backend

    ### 2. 路由与控制器 在“laravel-backend”中,路由是应用的入口点,用于定义URL与处理这些请求的控制器方法之间的关联。控制器负责处理这些请求,执行业务逻辑,并返回响应。Laravel 提供了简洁的路由定义方式和...

    Java EE 8 and Angular-Packt Publishing(2018)

    The demand for modern and high performing web enterprise applications is growing rapidly. No more is a basic ...

    lorawantm-backend-interfaces-v1.0.pdf

    This describes the standard interfaces and message flow between: 1) A Network Server and a Join Server 2) a Join Server and an Application Server 3) Two Network servers in the case of roaming traffic ...

    technologi-backend-test:技术后端测试

    技术后端测试指示结帐项目: git clone https://github.com/andrewf137/technologi-backend-test.git“ cd”到项目文件夹。 运行composer install 。 编辑&lt;project&gt;/config/config.php文件。 运行php init.php 。 这...

    PHP Microservices

    Learn about application design and structure to start implementing your application. Transform a monolithic application into microservices. Explore the best way to start implementing your application ...

    test_backend

    测试后端项目设置yarn install...且未在任何api中返回age和phone是私人的,不会在get用户api中返回任务2:用户身份验证在srv/routes.ts完成login api 任务3:迷你论坛第1部分:完成ForumPost类posts的API srv/routes.

    Xamarin Cross-platform Application Development(PACKT,2ed,2015)

    The book walks you through building a chat application, complete with a backend web service and native features such as GPS location, camera, and push notifications. Additionally, you'll learn how to...

Global site tag (gtag.js) - Google Analytics