作为程序员一定要保持良好的睡眠,才能好编程

PHP依赖工具之提交自定义包到Composer

发布时间:2019-09-02

项目中频繁使用的代码片段,通常会被封装成全局方法或类,以提高程序的复用性。但初始化新项目,手动引入会相对麻烦,此时可以提交到composer上实现自动安装。


1、创建composer 包

因为composer的代码都是托管在github上的所以开发者需要对git的操作相对比较熟悉。


2、操作大致步骤

1)使用github上创建应用仓库

2)使用composer在本地初始化

3)在本地开发类库

4)composer建立对应关系

5)  本地测试是否正常使用

6)提交到github应用仓库

7)提交到packagist后完成发布



 1)使用github上创建应用仓库


首先呢,需要一个github的账号和密码  

http://www.github.com


使用用户名和密码进行登录


第一、新建git仓库

登录成功以后,需要新建一个git仓库


g1.png


g2.png


完成以上操作后,克隆线上仓库副本到本地,作为类库开发的基础目录。


g3.png

g4.png


2)使用composer在本地初始化

创建本地包的第一个步就是初始化 composer.json 文件,初始化命令是 composer init

$ composer init


  Welcome to the Composer config generator



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

#填写包名,此格式确定包名的唯一性
Package name (<vendor>/<name>) [dell/first-composer]: songyongzhan/captcha
#包描述 可以不填 按回车键略过
Description []: captcha 生成验证码
#作者相关信息 或github用户名和邮箱 可以按n跳过
Author [一切源于你 <574482856@qq.com>, n to skip]: 宋永占
 Invalid author string.  Must be in the format: John Smith <john@example.com>
Author [一切源于你 <574482856@qq.com>, n to skip]: songyongzhan
 Invalid author string.  Must be in the format: John Smith <john@example.com>
Author [一切源于你 <574482856@qq.com>, n to skip]: n
#包发布的最低要求,填写dev可以让github上的代码直接同步到Packagist上,填写stable则需要打了tag包以后才能发布
Minimum Stability []: stable
#包类型,默认选择 library即可,其他还有项目、插件等
Package Type (e.g. library, project, metapackage, composer-plugin) []: library
License []:

Define your dependencies.
#是否定义当前的依赖项,可以输入no后按回车键略过
Would you like to define your dependencies (require) interactively [yes]? yes
#选择搜索依赖的包,这里输入php
Search for a package: php
#输入最低版本的约束,这里填写了php5.4
Enter the version constraint to require (or leave blank to use the latest version): >=5.4
#是否有其他的约束,此时没有,可以略过
Search for a package:
#是否以交互方式定义开发依赖项
Would you like to define your dev dependencies (require-dev) interactively [yes]? no

{
    "name": "songyongzhan/captcha",
    "description": "captcha 生成验证码",
    "type": "library",
    "require": {
        "php": ">=5.4"
    },
    "minimum-stability": "stable"
}

#确认下生成json文件 选择yes
Do you confirm generation [yes]? yes
#是否将vendor目录加入到忽略文件目录 选择yes
Would you like the vendor directory added to your .gitignore [yes]? yes
#是否立即安装依赖项 选择no
Would you like to install dependencies now [yes]? yes
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Writing lock file
Generating autoload files


3)在本地开发类库

在本地开发对应的类库


g5.png


在当前文件夹下面建立  src 文件夹 ,并在composer.json 文件中添加以下代码:


原composer.json 文件展示

{
    "name": "songyongzhan/captcha",
    "description": "captcha 生成验证码",
    "type": "library",
    "require": {
        "php": ">=5.4"
    },
    "minimum-stability": "stable"
}


添加代码后展示:

{
  "name": "songyongzhan/captcha",
  "description": "captcha 生成验证码",
  "type": "library",
  "autoload": {
    "psr-4": {
      "songyongzhan\\captcha\\": "src/lib"
    },
    "files": []
  },
  "require": {
    "php": ">=5.4"
  },
  "minimum-stability": "stable"
}


这是额外添加的。   psr-4 中的包文件与src/lib 这个只要能够对应上即可。

"autoload": {
    "psr-4": {
      "songyongzhan\\captcha\\": "src/lib"
    },
    "files": []
  },


在src文件夹下,建立 font、lib两个文件夹,font目录下是一个字体文件、lib下 是生成验证码的核心。

Captcha.php 代码展示如下:

<?php
/**
 * Created by PhpStorm.
 * User: DELL
 * Date: 2019/4/20
 * Time: 12:06
 * Email: 574482856@qq.com
 */

namespace songyongzhan\captcha;


class Captcha {


  public $width;
  public $height;
  public $length;
  public $code;
  public $img;

  public function __construct($code = '', $width = 70, $height = 25) {
    $this->height = $height;
    $this->width = $width;
    $this->code = $code;
    $this->img = imagecreatetruecolor($this->width, $this->height);
  }

  public function createImg($code = '') {

    if (!$code)
      $code = $this->code;

    if (!$code)
      throw new \InvalidArgumentException("生成验证码code不能为空");


    imagefill($this->img, 0, 0, imagecolorallocate($this->img, 255, 255, 255));

    for ($i = 0; $i < 20; $i++) { //干扰线
      $color = imagecolorallocate($this->img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
      imageline($this->img, mt_rand(0, $this->width), mt_rand(0, $this->height), mt_rand(0, $this->width), mt_rand(0, $this->height), $color);
    }

    for ($i = 0; $i < 200; $i++) { //背景
      $color = imagecolorallocate($this->img, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
      imagestring($this->img, 1, mt_rand(1, $this->width), mt_rand(1, $this->height), '*', $color);
    }

    $len = mb_strlen($this->code, 'utf-8');

    $size = $this->width / $len - 3;
    for ($i = 0; $i < strlen($code); $i++) { //验证码
      $color = imagecolorallocate($this->img, mt_rand(0, 100), mt_rand(0, 150), mt_rand(0, 200));
      //imagestring($this->img, 5, $i * $this->width / $len + mt_rand(1, 5), mt_rand(1, $this->height / 2), $code[$i], $color);

      imagettftext($this->img, $size, mt_rand(-50, 50), $i * $size + 5, $this->height - 5, $color
        , dirname(__FILE__) . '/../font/apple-4.ttf', $code[$i]);
    }


    ob_start();
    imagepng($this->img);
    $result = ob_get_contents();
    ob_end_clean();

    imagedestroy($this->img);

    return ['image' => 'data:image/png;base64,' . base64_encode($result)];

  }
}


核心内容开发完毕。


4)类库与composer建立对应关系

完成类库文件的编写后,还需要建立与composer的关系,主要操作就是把自定义类库加入到composer的自动加载机制中。在类库提交后,开飞着只需要在项目中引入全局的autoload.php文件(vendor/autoload.php) 就可以直接实例化和使用类库相关功能了。


在具体操作上,先 执行  


composer install

$ composer install
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Nothing to install or update
Generating autoload files


5)本地测试是否正常使用


新建 test.php

require "./vendor/autoload.php";

$code=mt_rand(1000,9999);
$captcha=new \songyongzhan\captcha\Captcha(strval($code));
$img=$captcha->createImg();

echo "<img src='".$img['image']."' />";


code1.jpg

code2.jpg

通过以上展示,证明本地是可以正常使用的。


6)提交到github应用仓库


#1新增文件
git add .

#2加入缓存区
git commit -m '//新增验证码生成类'

#3提交到远程仓库
$ git push -u origin master
fatal: HttpRequestException encountered.
   ▒▒▒▒▒▒▒▒ʱ▒▒▒▒
Username for 'https://github.com': 574482856@qq.com
Counting objects: 18, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (15/15), done.
Writing objects: 100% (18/18), 10.54 MiB | 331.00 KiB/s, done.
Total 18 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), done.
To https://github.com/songyongzhan/captcha.git
   187e815..7828d07  master -> master
Branch 'master' set up to track remote branch 'master' from 'origin'.

g6.jpg


看到代码已经成功提交到github上。



7)提交到packagist后完成发布


提交到composer包到Packagist主要有一下步骤:



https://packagist.org/

《1》、注册Packagist账号

     这里自行注册,我已经登录了

《2》、提交包的git仓库到Packagist上,操作步骤

g7.jpg



点击 submit 出现这样的一个窗口,将我们github上的 地址,粘贴过来,如图所示





g8.jpg


我们需要注意的是:composer.json 文件中 

"name": "songyongzhan/laravel_autocheck",

name 不能包含大写字母,这样会引起提示信息,不能注册成功。



https://github.com/songyongzhan/captcha.git



g9.jpg

这里已经有很多个图形验证码生成的类了,不需要理会,直接发布我们自己的类,就可以了。



提交成功后,效果如下图:


g10.jpg



《3》、发布正式版本

当Composer获取测试版本(dev)进行依赖安装时,会自动同步github上的最新代码。

但是我们使用的stable 稳定版,需要在Github上添加相应的标签(Tag)。

下面简单的操作步骤:

1、本地创建Tag标签推送到版本库

git tag -a v1.0.0 -m='初始版本'


查看 git tag  可以看到 v1.0.0 这个版本


这时推送到 远程服务器

$ git push origin v1.0.0


DELL@DESKTOP-HEOND63 MINGW64 /e/phpStudy/WWW/firstComposer (master)
$ git tag -a v1.0.0 -m='初始版本'

DELL@DESKTOP-HEOND63 MINGW64 /e/phpStudy/WWW/firstComposer (master)
$ git tag
v1.0.0

DELL@DESKTOP-HEOND63 MINGW64 /e/phpStudy/WWW/firstComposer (master)
$ git push origin v1.0.0
fatal: HttpRequestException encountered.
   ▒▒▒▒▒▒▒▒ʱ▒▒▒▒
Username for 'https://github.com': 574482856@qq.com
Counting objects: 1, done.
Writing objects: 100% (1/1), 185 bytes | 185.00 KiB/s, done.
Total 1 (delta 0), reused 0 (delta 0)
To https://github.com/songyongzhan/captcha.git
 * [new tag]         v1.0.0 -> v1.0.0

v1.jpg

v2.jpg

在github上已经看到版本号了。


2、更新packagist

v3.jpg

到packagist上,点击 update 按钮进行更新,稍后 右侧就会出现版本号信息。如图所示。



《4》、安装使用


使用方法:

新建目录 demo ,并在此目录下执行


composer require songyongzhan/captcha


g11.jpg


DELL@DESKTOP-HEOND63 MINGW64 /e/phpStudy/WWW/demo
$ composer require songyongzhan/captcha
Using version ^1.0 for songyongzhan/captcha
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing songyongzhan/captcha (v1.0.0): Downloading (100%)
Writing lock file
Generating autoload files

DELL@DESKTOP-HEOND63 MINGW64 /e/phpStudy/WWW/demo


demo1.jpg


安装完成后,在根目录下创建 test.php 

require './vendor/autoload.php';

$code=['1234','cde1','AGy2','8888'];


$sortIndex=array_rand($code,1);

$captcha=new \songyongzhan\captcha\Captcha(strval($code[$sortIndex]));
$img =$captcha->createImg();

echo "<img src='".$img['image']."'/>";

运行


结果显示如下:

d1.jpg


d2.jpg


到此,完成。。。