Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
composer.json中的 “bin” 字段如何创建命令行工具_创想鸟

composer.json中的 “bin” 字段如何创建命令行工具

“bin”字段用于注册PHP命令行工具,Composer会将指定脚本链接到vendor/bin目录。1. 配置”bin”数组指向可执行文件;2. 确保脚本含shebang并设可执行权限;3. 安装后通过php vendor/bin/命令运行;4. 全局安装需将~/.composer/vendor/bin加入PATH。

composer.json中的

composer.json 中使用 “bin” 字段可以将 PHP 脚本注册为全局或项目级别的命令行工具。当你通过 Composer 安装一个包含 “bin” 配置的包时,Composer 会把指定的可执行脚本链接到 vendor/bin 目录,并在全局 Composer bin 目录(如 ~/.composer/vendor/bin)中创建快捷方式(如果设置了全局安装)。

1. 理解 “bin” 字段的作用

“bin” 字段是一个数组,列出可执行的 PHP 脚本文件路径。这些文件通常是带有 #!/usr/bin/env php 头部的 PHP 脚本,能够直接在命令行运行。

例如:

{ “name”: “your-vendor/your-tool”, “bin”: [ “bin/my-command” ]}

当这个包被安装时,Composer 会把 bin/my-command 文件复制或符号链接到 vendor/bin/my-command,你可以通过以下方式运行它:

php vendor/bin/my-command

如果你的 Composer 全局 bin 目录在系统 PATH 中,还可以直接输入命令名运行(前提是已全局 require)。

2. 创建可执行的命令行脚本

确保你的脚本具备可执行权限并包含正确的 shebang 行。

示例:创建文件 bin/my-command

#!/usr/bin/env php<?php// 检查是否以 CLI 模式运行if (php_sapi_name() !== 'cli') { exit('This script must be run from the command line.' . PHP_EOL);}echo "Hello from my custom command!" . PHP_EOL;

设置脚本可执行(Linux/macOS):

行者AI 行者AI

行者AI绘图创作,唤醒新的灵感,创造更多可能

行者AI 100 查看详情 行者AI chmod +x bin/my-command

3. 在 composer.json 中配置 bin

在你的项目的 composer.json 中添加 bin 字段:

{ “name”: “example/cli-tool”, “autoload”: { “psr-4”: { “Example”: “src/” } }, “bin”: [ “bin/my-command” ], “require”: {}}

执行 composer install 后,Composer 会自动把 bin/my-command 映射到 vendor/bin/my-command

4. 使用你的命令行工具

安装完成后,可以直接运行:

php vendor/bin/my-command

输出结果:

Hello from my custom command!

如果你想让命令更简洁(比如直接输入 my-command),可以将 Composer 的全局 bin 目录加入系统环境变量 PATH,并使用 composer global require your-vendor/your-tool 安装。

基本上就这些。只要脚本可执行、路径正确、bin 字段配置无误,Composer 就能帮你把 PHP 脚本变成可用的命令行工具。不复杂但容易忽略细节,比如 shebang 和权限。注意别拼错文件路径。

以上就是composer.json中的 “bin” 字段如何创建命令行工具的详细内容,更多请关注php中文网其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/256321.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
win10怎么进行磁盘碎片整理_使用Windows工具对硬盘进行碎片整理与优化
上一篇 2025年11月4日 07:26:58
晨报|8月PS Plus阵容公开 COD21第五赛季预告公开
下一篇 2025年11月4日 07:27:05

相关推荐

发表回复

登录后才能评论
关注微信