一、前言
Composer 是 PHP 用来管理依赖(dependency)关系的工具。我们不仅要学会使用别人提供的包,更要学会制作和分享自己的软件包,下面演示如何创建一个自己的 Composer 包。

准备工作:
注册 Github 账号
注册 Packagist 账号
二、实践
本案例演示如何创建一个第三方消息推送(极光推送)的包。

1. 创建 Github 仓库
登录 Github,创建仓库 yanlongma/push,并将代码克隆到本地:

$ git clone https://github.com/yanlongma/push.git
1
2. 创建 Composer 配置文件
进入项目根目录,创建 Composer 配置文件 composer.json,可以使用命令 compser init 创建也可以手动创建,最终文件内容大体如下:
{
“name”: “yanlongma/push”,
“description”: “Third party message push”,
“authors”: [
{
“name”: “Yanlong Ma”
}
],
“license”: “MIT”,
“require”: {
“php”: “>=5.4”
},
“autoload”: {
“psr-4”: {
“YanlongMa\\Push\\”: “src/”
}
}
}

3. 提交代码到 Github

根据自己需要实现的功能编写代码,本项目最终项目结构如下:

.git/
.gitignore
composer.json
README.md
src/
Client.php
JPush.php

代码编写完成且测试没问题后提交代码到 Github。

4. 发布包到 Packagist
登录 Packagist,检出 https://github.com/YanlongMa/push.git 仓库的代码,系统会根据仓库中 composer.json 文件自动设置包的相关信息。

5. 设置 Packagist 中的包自动更新
如果不设置自动同步,每次 Github 中的代码更新,需要在对应包中手动更新,所以建议设置自动更新。步骤如下:

进入 yanlongma/push 仓库,选择 “Settings -> Integrations & services”;
点击 “Add service”,选择 “Packagist”;
填写你的 Packagist 账号对应的信息(登录后点击查看https://packagist.org/profile/ )
配置完成后,点击右上角的“Test service”,如果出现 “Okay, the test payload is on its way.”,则说明配置成功。
6. 使用共享包
发布包到 Packagist 后,根据包名就可以搜索和使用该包了,在自己的项目中申明该包依赖:

$ composer require yanlongma/push

该包的具体使用可以查看 https://github.com/yanlongma/push。

注:
– 发布包到 Packagist 后,可能过几分钟才能在客户端 search 到;
– 没有打 tag 的要指定 dev,完整命令composer require “yanlongma/push @dev”