PHP 常用代碼段

介紹

其實在寫代碼的過程中,我們經常需要上網找各種資料,大部分是代碼段,比如說:怎麼轉碼,怎麼發送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);
    }
}

待補充

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章