1. 程式人生 > >手把手教你擼一個composer擴充套件

手把手教你擼一個composer擴充套件

PHP程式設計師都是使用composer進行包管理,平時更多的是require別人開發的擴充套件,其實自己寫擴充套件也是非常容易的,本文已一個簡單的例子來手把手教你寫自己的composer擴充套件,本例子是基於yii2自帶的log,增加釘釘機器人作為Target,實現錯誤日誌實時推送到釘釘群,並可以@指定的人或@所有人

1. 初始化專案

在github建立專案yii2-dingtalk-robot

https://github.com/philpm/yii2-dingtalk-robot.git

在本地建立工程目錄並新增遠端分支

mkdir yii2-dingtalk-robot
cd yii2-dingtalk-robot
# 初始化git倉庫
git init
# 新增遠端分支
git remote add origin https://github.com/philpm/yii2-dingtalk-robot.git

2. 編寫擴充套件類

使用composer init命令初始化composer.json檔案

composer init                                                                                   


  Welcome to the Composer config generator



This command will guide you through creating your composer.json config.

Package name (<vendor>/<name>) [qinphil/yii2-dingtalk-robot]:
Description []:
Author [秦豔飛 <[email protected]>, n to skip]:
Minimum Stability []:
Package Type (e.g. library, project, metapackage, composer-plugin) []:
License []:

Define your dependencies.

Would you like to define your dependencies (require) interactively [yes]? no
Would you like to define your dev dependencies (require-dev) interactively [yes]? no

{
    "name": "qinphil/yii2-dingtalk-robot",
    "authors": [
        {
            "name": "秦豔飛",
            "email": "[email protected]"
        }
    ],
    "require": {}
}

Do you confirm generation [yes]? yes
Would you like the vendor directory added to your .gitignore [yes]? yes

手動修改composer.json檔案,增加自動載入配置

{
    "name": "philpm/yii2-dingtalk-robot",
    "description": "使用釘釘群聊機器人做為target",
    "type": "library",
    "license": "MIT",
    "authors": [
        {
            "name": "Phil Qin",
            "email": "[email protected]"
        }
    ],
    "minimum-stability": "0.0.2",
    "require": {
        "yiisoft/yii2": "~2.0.0",
        "php": ">=5.6.0"
    },
    "autoload": {
        "psr-4": {
            "philpm\\dingtalk\\": "src/"
        }
    }
}


coding

在src目錄裡建立Target.php檔案,程式碼如下

<?php
/**
 * yii2-dingtalk-robot
 * User: Phil<[email protected]>
 * DateTime: 2019/7/8 11:49 AM
 * 使用釘釘機器人作為日誌的target
 */

namespace philpm\dingtalk;

use yii\base\InvalidConfigException;

class Target extends \yii\log\Target
{
    /**
     * @var string 機器人access_token
     */
    public $robotToken;

    /**
     * @var array 需要at的人的手機號 eg. [mobile1,mobile2]
     */
    public $at;

    /**
     * @var boolean 是否at所有人
     */
    public $isAtAll = false;

    public function export()
    {
        $text = implode("\n", array_map([$this, 'formatMessage'], $this->messages)) . "\n";

        $data = [
            "msgtype" => "text",
            "text" => [
                "content" => $text
            ],
            "at" => [
                "atMobiles" => $this->at,
                "isAtAll" => $this->isAtAll
            ]
        ];

        $this->curl_post_ssl($data, "https://oapi.dingtalk.com/robot/send?access_token=" . $this->robotToken);

    }

    /**
     *  POST請求
     */
    protected function curl_post_ssl($data = null, $url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $res = curl_exec($ch);
        if (curl_errno($ch)) {
            throw new InvalidConfigException('釘釘機器人請求資料失敗: ' . curl_error($ch));
        }
        curl_close($ch);
        return json_decode($res, true);
    }
}

3. 提交到github

增加.gitignore 為 git 忽略一些檔案,增加 README.md 為專案增加描述

# composer vendor dir
/vendor

# composer itself is not needed
composer.phar
composer.lock

程式碼push到github,使用了git flow輔助

git flow init
git flow release start 0.0.1
git flow release finish 0.0.1
git push  -u origin master --tags

4. 登入packagist, 如沒有賬號先註冊一下

點選 Submit ,輸入你的github專案地址然後點Check按鈕,可能會遇到名稱空間同名的問題,會提示你,如果沒有意外的話包就生成了,訪問地址:https://packagist.org/packages/philpm/yii2-dingtalk-robot

5. 測試使用自己的包

在yii2工程目錄下,執行:

php composer.phar require --prefer-dist philpm/yii2-dingtalk-robot "~0.0.2"

順利的話vendor目錄下會生成philpm/yii2-dingtalk-robot目錄,src目錄裡有Target.php

修改yii2的配置檔案,高階版在common/config/main-local.php

....
'components' => [
    'log' => [
        'targets' => [
            [
                'class' => 'phil\dingtalk\Target',
                'levels' => ['error', 'warning'],
                'categories' => ['api', 'app'],
                'robotToken'=>'******', // your dingding access_token
                'at'=> [13800138000,18888888888], // the mobile of the receiver
                'isAtAll'=>true, // at 所有人
                'except' => [
                    'yii\web\HttpException:404',
                ],
            ],
        ]
....

然後就可以是用系統日誌呼叫的方式去給釘釘推送一些錯誤告警,如下:

Yii::warning('簡訊通道賬戶餘額不足,請及時充值','api');

如不需要環境變數可設定'logVars' => []

--

另外每次給github上push帶tag的版本時packagist.org裡的包會自動更新

PHP程式設計師都是使用composer進行包管理,平時更多的是require別人開發的擴充套件,其實自己寫擴充套件也是非常容易的,本文已一個簡單的例子來手把手教你寫自己的composer擴充套件,本例子是基於yii2自帶的log,增加釘釘機器人作為Target,實現錯誤日誌實時推送到釘釘群,並可以@指定的人或@所有人

1. 初始化專案

在github建立專案yii2-dingtalk-robot

https://github.com/philpm/yii2-dingtalk-robot.git

在本地建立工程目錄並新增遠端分支

mkdir yii2-dingtalk-robot
cd yii2-dingtalk-robot
# 初始化git倉庫
git init
# 新增遠端分支
git remote add origin https://github.com/philpm/yii2-dingtalk-robot.git

2. 編寫擴充套件類

使用composer init命令初始化composer.json檔案

composer init                                                                                   


  Welcome to the Composer config generator



This command will guide you through creating your composer.json config.

Package name (<vendor>/<name>) [qinphil/yii2-dingtalk-robot]:
Description []:
Author [秦豔飛 <[email protected]>, n to skip]:
Minimum Stability []:
Package Type (e.g. library, project, metapackage, composer-plugin) []:
License []:

Define your dependencies.

Would you like to define your dependencies (require) interactively [yes]? no
Would you like to define your dev dependencies (require-dev) interactively [yes]? no

{
    "name": "qinphil/yii2-dingtalk-robot",
    "authors": [
        {
            "name": "秦豔飛",
            "email": "[email protected]"
        }
    ],
    "require": {}
}

Do you confirm generation [yes]? yes
Would you like the vendor directory added to your .gitignore [yes]? yes

手動修改composer.json檔案,增加自動載入配置

{
    "name": "philpm/yii2-dingtalk-robot",
    "description": "使用釘釘群聊機器人做為target",
    "type": "library",
    "license": "MIT",
    "authors": [
        {
            "name": "Phil Qin",
            "email": "[email protected]"
        }
    ],
    "minimum-stability": "0.0.2",
    "require": {
        "yiisoft/yii2": "~2.0.0",
        "php": ">=5.6.0"
    },
    "autoload": {
        "psr-4": {
            "philpm\\dingtalk\\": "src/"
        }
    }
}


coding

在src目錄裡建立Target.php檔案,程式碼如下

<?php
/**
 * yii2-dingtalk-robot
 * User: Phil<[email protected]>
 * DateTime: 2019/7/8 11:49 AM
 * 使用釘釘機器人作為日誌的target
 */

namespace philpm\dingtalk;

use yii\base\InvalidConfigException;

class Target extends \yii\log\Target
{
    /**
     * @var string 機器人access_token
     */
    public $robotToken;

    /**
     * @var array 需要at的人的手機號 eg. [mobile1,mobile2]
     */
    public $at;

    /**
     * @var boolean 是否at所有人
     */
    public $isAtAll = false;

    public function export()
    {
        $text = implode("\n", array_map([$this, 'formatMessage'], $this->messages)) . "\n";

        $data = [
            "msgtype" => "text",
            "text" => [
                "content" => $text
            ],
            "at" => [
                "atMobiles" => $this->at,
                "isAtAll" => $this->isAtAll
            ]
        ];

        $this->curl_post_ssl($data, "https://oapi.dingtalk.com/robot/send?access_token=" . $this->robotToken);

    }

    /**
     *  POST請求
     */
    protected function curl_post_ssl($data = null, $url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $res = curl_exec($ch);
        if (curl_errno($ch)) {
            throw new InvalidConfigException('釘釘機器人請求資料失敗: ' . curl_error($ch));
        }
        curl_close($ch);
        return json_decode($res, true);
    }
}

3. 提交到github

增加.gitignore 為 git 忽略一些檔案,增加 README.md 為專案增加描述

# composer vendor dir
/vendor

# composer itself is not needed
composer.phar
composer.lock

程式碼push到github,使用了git flow輔助

git flow init
git flow release start 0.0.1
git flow release finish 0.0.1
git push  -u origin master --tags

4. 登入packagist, 如沒有賬號先註冊一下

點選 Submit ,輸入你的github專案地址然後點Check按鈕,可能會遇到名稱空間同名的問題,會提示你,如果沒有意外的話包就生成了,訪問地址:https://packagist.org/packages/philpm/yii2-dingtalk-robot

5. 測試使用自己的包

在yii2工程目錄下,執行:

php composer.phar require --prefer-dist philpm/yii2-dingtalk-robot "~0.0.2"

順利的話vendor目錄下會生成philpm/yii2-dingtalk-robot目錄,src目錄裡有Target.php

修改yii2的配置檔案,高階版在common/config/main-local.php

....
'components' => [
    'log' => [
        'targets' => [
            [
                'class' => 'phil\dingtalk\Target',
                'levels' => ['error', 'warning'],
                'categories' => ['api', 'app'],
                'robotToken'=>'******', // your dingding access_token
                'at'=> [13800138000,18888888888], // the mobile of the receiver
                'isAtAll'=>true, // at 所有人
                'except' => [
                    'yii\web\HttpException:404',
                ],
            ],
        ]
....

然後就可以是用系統日誌呼叫的方式去給釘釘推送一些錯誤告警,如下:

Yii::warning('簡訊通道賬戶餘額不足,請及時充值','api');

如不需要環境變數可設定'logVars' => []

--

另外每次給github上push帶tag的版本時packagist.org裡的包會自動