版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pengjian444/article/details/83863810
文章目录
介绍
其实在写代码的过程中,我们经常需要上网找各种资料,大部分是代码段,比如说:怎么转码,怎么发送http请求,怎么建立socket连接等等,这部分工作耗时而且如果稍加整理的话可以大大节省我们的开发时间,对开发来说是很重要的。这里我稍微整理一下自己平时在写php代码的时候常用的代码段,做一个简单的集合,暂时可能只几个片段,之后多了会考虑做一个合集放到github上。然后也欢迎大家来讨论
代码段
编写ini文件并解析
- ini文件格式介绍
ini文件是一种极其简单的配置文件,只支持key-value的存储格式。可以分节编写,但是读取的时候并不会做区分。 - ini文件示例 [from wikipadie]
; last modified 1 April 2001 by John Doe
[owner]
name=John Doe
organization=Acme Products
[database]
server=192.0.2.42 ; use IP address in case network name resolution is not working
port=143
file="acme payroll.dat"
- php解析ini文件方法
php解析特别方便
$conf = parse_ini_file('file_path');
$conf['name']; // 按照key-value的模式读取
mysql
1.创建mysql连接
这里给出常用的库文件,使用单例模式来避免重复连接~
class Db {
/**
* @var mysqli | null
*/
private static $conn = null;
/**
* 获取数据库连接
* @return mysqli | null
*/
public static function getConn() {
if (!is_null(Db::$conn)) {
return Db::$conn;
} else {
$conf = parse_ini_file('./conf/db.ini'); // 读取数据库连接的配置文件
try {
Db::$conn = new mysqli($conf['ip'], $conf['username'], $conf['password'], $conf['database'], $conf['port']);
} catch (Exception $e) {
Log::notice("数据库连接错误" . $e->getMessage());
}
if (Db::$conn->connect_errno) {
$errMsg = Db::$conn->connect_error;
Log::notice("数据库连接错误:" . $errMsg);
Db::$conn->close();
}
return Db::$conn;
}
}
}
guzzle http
1. 使用guzzle发送http-get请求
- 同步版本
/**
* @return string
*/
private function SendHttpGet() {
$url = 'http://api.github.com/user';
$client = new GuzzleHttp\Client();
try {
// 同步方法
$res = $client->get($url, [
'timeout' => '1000',
'headers' => [
'Accept' => 'application/json',
],
'query' => [
'tag' => 'example',
],
]);
return $res->getBody()->getContents();
} catch (\GuzzleHttp\Exception\RequestException $e) {
echo $e->getMessage();
return '';
}
}
- 异步版本
/**
*/
private function SendAsyncHttpGet() {
$url = 'http://api.github.com/user';
$client = new GuzzleHttp\Client();
// 异步方法
$promise = $client->getAsync($url, [
'timeout' => '1000',
'headers' => [
'Accept' => 'application/json',
],
'query' => [
'tag' => 'example',
],
]);
$promise->then(
function (\Psr\Http\Message\ResponseInterface $res) {
echo $res->getBody()->getContents();
},
function (\GuzzleHttp\Exception\RequestException $res) {
echo $res->getMessage() . "\n";
}
);
}
2. 使用guzzle发送http-post请求
- 同步版本
/**
* @return string
*/
private function SendHttpPost() {
$url = 'http://api.github.com/user';
$client = new GuzzleHttp\Client();
try {
// 同步方法
$res = $client->post($url, [
'timeout' => '1000',
'headers' => [
'Accept' => 'application/json',
],
'body' => 'body example',
'form_params' => [
'name' => 'Jone',
],
'query' => [
'tag' => 'example',
],
]);
return $res->getBody()->getContents();
} catch (\GuzzleHttp\Exception\RequestException $e) {
echo $e->getMessage();
return '';
}
}
- 异步版本
/**
*/
private function SendAsyncHttpPost() {
$url = 'http://api.github.com/user';
$client = new GuzzleHttp\Client();
// 异步方法
$promise = $client->postAsync($url, [
'timeout' => '1000',
'headers' => [
'Accept' => 'application/json',
],
'body' => 'body example',
'form_params' => [
'name' => 'Jone',
],
'query' => [
'tag' => 'example',
],
]);
$promise->then(
function (\Psr\Http\Message\ResponseInterface $res) {
echo $res->getBody()->getContents();
},
function (\GuzzleHttp\Exception\RequestException $res) {
echo $res->getMessage() . "\n";
}
);
}
输出中间结果
1. 到控制台
public static function toConsole($message) {
fwrite(STDERR, print_r($message));
}
2. 到文件
public static function toFile($filename, $message) {
$fileHandler = fopen($filename, 'w');
fwrite($fileHandler, $message);
}
使用monolog输出日志
下面的代码只给出部分notice&warn的函数,其他fatal类似的添加
<?php
/**
* Created by PhpStorm.
* User: pengjian05
* Date: 2018/11/8
* Time: 15:19
*/
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
class TheLog {
/**
* @var Logger
*/
private static $log = null;
public static function getInstance() {
if (is_null(self::$log)) {
self::$log = new Logger('logger_name');
try {
$streamH = new StreamHandler(".\\logs\\the.log", Logger::NOTICE);
self::$log->pushHandler($streamH);
} catch (InvalidArgumentException $e) {
echo $e->getMessage();
self::$log = null;
} catch (Exception $e) {
echo $e->getMessage();
self::$log = null;
}
return self::$log;
} else {
return self::$log;
}
}
public static function addNotice($message) {
$logger = self::getInstance();
if (!is_null($logger)) {
$logger->notice($message);
return true;
} else {
return false;
}
}
public static function addWarn($message) {
$logger = self::getInstance();
if (!is_null($logger)) {
$logger->warn($message);
return true;
} else {
return false;
}
}
}
最后日志输出为:
[2018-11-08 09:28:47] logger_name.NOTICE: my message [] []
快速创建phpunit测试代码
这里就给出上面测试monolog输出的例子吧,善用单元测试,真的能在迭代&开发中节省不少的时间
<?php
/**
* Created by PhpStorm.
* User: pengjian05
* Date: 2018/11/8
* Time: 15:35
*/
require 'vendor/autoload.php';
use PHPUnit\Framework\TestCase;
include './log/mono.php';
class TestMonolog extends TestCase {
public function testAddNotice() {
TheLog::addNotice("my message");
$this->assertEquals(0, 0);
}
public function testGetInstance() {
$log = TheLog::getInstance();
$this->assertNotEquals(null, $log);
}
}