一、初始化(生成composer.json文件)
composer init
#输入你要创建的composer包项目命名空间
Package name (<vendor>/<name>) [root/tiny-laravel]: #haveyb/tiny-laravel
#输入composer包的描述
Description []:#this is a tiny laravel haveyb
#输入作者信息。前面是作者名称,后面用<>包住邮箱地址
Author [, n to skip]: #haveyb <haveyb@163.com>
#输入版本稳定性,stable, RC, beta, alpha, dev
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]?#示例:
Would you like to define your dependencies (require) interactively [yes]? yes
Search for a package: php
Enter the version constraint to require (or leave blank to use the latest version): >=7.1.3#如果还有其他依赖,则继续填写,否则直接回车
Search for a package:
Would you like to define your dev dependencies (require-dev) interactively [yes]? no
{"name": "haveyb/tiny-laravel","description": "this is a tiny laravel haveyb","type": "library","require": {"php": ">=7.1.3"},"license": "MIT","authors": [{"name": "haveyb","email": "haveyb@163.com"}],"minimum-stability": "dev"
}
Do you confirm generation [yes]? yes
#是否现在安装依赖
Would you like to install dependencies now [yes]? no
配置psr-4自动加载
#在composer.json中添加如下代码
"autoload":{"psr-4":{"haveyb\\TinyLaravel\\":"./src/"}
},
添加上面代码后的composer.json文件
{"name": "haveyb/tiny-laravel","description": "this is a tiny laravel haveyb","type": "library","require": {"php": ">=7.1"},"license": "MIT","authors": [{"name": "haveyb","email": "haveyb@163.com"}],"minimum-stability": "dev","autoload":{"psr-4":{"haveyb\\TinyLaravel\\":"./src/"}}
}
生成自动加载文件
composer update#也可以使用composer install命令,只不过composer update更常用
执行该命令后,就会发现,目录下生成了一些文件,这些文件就是自动加载所用的文件,如图:
二、开发composer包并测试
1、创建目录结构
在包目录下创建src目录,我这里的包目录是在 /data/tiny-laravel
cd /data/tiny-laravel
mkdir src
cd src
mkdir database
touch MySQL.php
2、向 MySQL.php 文件添加如下测试内容
<?php
declare(strict_types = 1);
namespace haveyb\TinyLaravel\database;class MySQL
{/*** 测试用例** @return string* @author cyf*/public function getDatabase() : string{return 'this is get database function';}
}
3、在项目中实例化这个类,并访问这个方法,如果成功,说明composer包开发成功,之后根据需求定制开发即可。
我这里为了方便,直接在网站根目录访问的index.php。
index.php
<?php
require './vendor/autoload.php';
use haveyb\TinyLaravel\database\MySQL;$mysql = new MySQL();
echo $mysql->getDatabase();
结果是this is get database function,说明定义并加载成功,之后可以根据需求定制开发,然后在项目中实例化后引用相应方法即可。
注意:如果出错,着重检查命名空间和引入是否正确和规范。
4、结语
现在,我们可以开始定制开发了,就像我们使用的阿里巴巴的 oss composer包一样。
具体包的加载过程,这里不细说,不过有一个文件,大家应该要知道,位于 tiny-laravel/vendor/composer/autoload_psr4.php。
它长这个样子:
<?php// autoload_psr4.php @generated by Composer$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);return array('haveyb\\TinyLaravel\\' => array($baseDir . '/src'),'yii\\gii\\' => array($vendorDir . '/yiisoft/yii2-gii/src'),
);
三、发布composer到packagist