手把手教你發佈本身的 Composer 包

1、前言

Composer 是 PHP 用來管理依賴(dependency)關係的工具。咱們不只要學會使用別人提供的包,更要學會製做和分享本身的軟件包,下面演示如何建立一個本身的 Composer 包。php

準備工做:

  1. 註冊 Github 帳號
  2. 註冊 Packagist 帳號

2、實踐

本案例演示如何建立一個第三方消息推送(極光推送)的包。html

1. 建立 Github 倉庫

登陸 Github,建立倉庫 yanlongma/push,並將代碼克隆到本地:git

$ git clone https://github.com/yanlongma/push.git

2. 建立 Composer 配置文件

進入項目根目錄,建立 Composer 配置文件 composer.json,能夠使用命令 compser init 建立也能夠手動建立,最終文件內容大致以下:github

{
    "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

根據本身須要實現的功能編寫代碼,本項目最終項目結構以下:json

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

代碼編寫完成且測試沒問題後提交代碼到 Github。composer

4. 發佈包到 Packagist

登陸 Packagist,檢出 https://github.com/YanlongMa/push.git 倉庫的代碼,系統會根據倉庫中 composer.json 文件自動設置包的相關信息。工具

5. 設置 Packagist 中的包自動更新

若是不設置自動同步,每次 Github 中的代碼更新,須要在對應包中手動更新,因此建議設置自動更新。步驟以下:測試

  1. 進入 yanlongma/push 倉庫,選擇 "Settings -> Integrations & services";
  2. 點擊 "Add service",選擇 「Packagist」;
  3. 填寫你的 Packagist 帳號對應的信息(登陸後點擊查看https://packagist.org/profile/
  4. 配置完成後,點擊右上角的「Test service」,若是出現 「Okay, the test payload is on its way.」,則說明配置成功。

6. 使用共享包

發佈包到 Packagist 後,根據包名就能夠搜索和使用該包了,在本身的項目中申明該包依賴:ui

$ composer require yanlongma/push

該包的具體使用能夠查看 https://github.com/yanlongma/pushcode

  • 發佈包到 Packagist 後,可能過幾分鐘才能在客戶端 search 到;
  • 沒有打 tag 的要指定 dev,完整命令composer require "yanlongma/push @dev"

本文首發於馬燕龍我的博客,歡迎分享,轉載請標明出處。 馬燕龍我的博客:http://www.mayanlong.com 馬燕龍我的微博:http://weibo.com/imayanlong 馬燕龍Github主頁:https://github.com/yanlongma

相關文章
相關標籤/搜索