本站点已停止更新,内容已迁移至 lh1010.com
good luck to you

创建自己的composer包

文章目录

简要说明

  • 本文主要讲解如何制作自己的Composer包
  • 涉及知识点:Composer、PHP、Git

生成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>) [administrator/lh1010]: lh1010/lh1010
Description []: lh1010
Author [Jasper <610392592@qq.com>, n to skip]:
Minimum Stability []: dev
Package Type (e.g. library, project, metapackage, composer-plugin) []: library
License []: MIT

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": "lh1010/lh1010",
    "description": "lh1010",
    "type": "library",
    "license": "MIT",
    "authors": [
        {
            "name": "Jasper",
            "email": "610392592@qq.com"
        }
    ],
    "minimum-stability": "dev",
    "require": {}
}

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

生成后的composer.json

{
    "name": "lh1010/lh1010",
    "description": "lh1010",
    "type": "library",
    "license": "MIT",
    "authors": [
        {
            "name": "Jasper",
            "email": "610392592@qq.com"
        }
    ],
    "minimum-stability": "dev",
    "require": {}
}

修改composer.json

{
    "name": "lh1010/lh1010",
    "description": "lh1010",
    "type": "library",
    "license": "MIT",
    "authors": [
        {
            "name": "Jasper",
            "email": "610392592@qq.com"
        }
    ],
    "minimum-stability": "dev",
    "require": {
        "php": ">=5.4.0"
    },
    "autoload": {
        "psr-4": {
            "Lh1010\\": "src/"
        }
    }
}

创建src相关文件

在当面目录下创建src/Tools.php测试文件

<?php

namespace Lh1010;

class Tools
{

    public static function demo()
    {
        echo 'This is demo';
    }

}

安装、生成命名空间和目录的映射关系

$ composer install

此时会在vendor/composer/autoload_psr4.php中生成命名空间和目录的映射关系,被包在一个数组中:

<?php

// autoload_psr4.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Lh1010\\' => array($baseDir . '/src'),
);

测试

当前目录下创建index.php

<?php 

require './vendor/autoload.php';

use Lh1010\Tools;

Tools::demo();

目录结构

提交至packagist

上传至github

将包上传至github(此处省略过程)。注意:.gitignore屏蔽vendor文件。

创建packagist账号

packagist地址:packagist.org

提交至packagist

到这里,composer包就提交成功了,如图

网上有说同步的问题,但在测试当天(19-03-21),通过 packagist 提交后,与 github 已自动同步。

可能原因:使用 github 账号授权登录packagist(待验证)。

测试

composer require lh1010/lh1010 dev-master

当前目录下创建index.php

<?php 

require './vendor/autoload.php';

use Lh1010\Tools;

Tools::demo();

发布正式版

版本默认是dev-master,Composer包的版本号会从Git的tag中同步过来,因此先设置项目代码的tag,回到项目目录

$ git tag 1.0.0
$ git push --tag
composer lh1010/lh1010
原文链接:,转发请注明来源!

发表评论