手把手教你撸一个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 (/) [qinphil/yii2-dingtalk-robot]:
Description []:
Author [秦艳飞 , 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文件,代码如下
* 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里的包会自动更新