[英]Get version of Composer package(s) in PHP, without using the command line
Is there a way to get the version for a package installed with Composer, and which is currently used by an application, without invoking composer show -i
or anything similar?有没有办法获取与 Composer 一起安装的软件包的版本,并且当前由应用程序使用,而无需调用
composer show -i
或任何类似的东西?
I want to determinate the versions currently used by the application and and show an alert if some packages need to be updated, and eventually auto update.我想确定应用程序当前使用的版本,并在需要更新某些包并最终自动更新时显示警报。
For the current task, I think the appropriate solution will be the following.对于当前的任务,我认为合适的解决方案如下。
Composer creates a installed.json file under vendor/composer , which contains all the information about the installed packages, as they are defined. Composer 在vendor/composer下创建一个installed.json文件,其中包含有关已安装软件包的所有信息,如定义的那样。
The file looks something similar to this.该文件看起来与此类似。
[
{
"name": "vendor_X/package_Y",
"version": "1.0.0",
"version_normalized": "1.1.0.0",
"source": {},
"dist": {},
"require": {},
"require-dev": {},
other data about the package
},
{"..other package's data..": ""},
{"...": ""}
]
A simple solution will be using the following code.一个简单的解决方案是使用以下代码。
$data = array();
$packages = json_decode(file_get_contents('../vendor/composer/installed.json'));
// Assuming that the project root is one level above the web root.
foreach ($packages as $package) {
$data[$package['name']] = $package['version'];
}
// Make a cURL request to packagist.org to get the package data
// https://packagist.org/packages/vendor_X/package_Y.json
// The output is something like the following
/*
{
"package": {
"name": "omnipay/dummy",
"versions": {
"dev-master": {},
"v1.1.0": {},
"v1.0.0": {}
},
"type": "library",
}
}
*/
$packagist = json_decode($packagist_reponse_as_json);
if (strcmp($data['vendor_X/package_Y'], $packagist['package']['versions'][1]) < 0) {
// Fire a composer update, send email alert, show notification, or call the president.
}
The solution above is the simplest and a little ugly, but it shows the key points, namely, where to get local versions for packages and how to get the package versions from Composer.上面的解决方案是最简单的,也有点丑,但它展示了关键点,即从哪里获取包的本地版本以及如何从Composer获取包版本。
A more practical solution should employ caching and should not be done during normal application operation;更实用的解决方案应该使用缓存,而不应该在正常的应用程序操作期间进行; a better solution would be using a cron job.
更好的解决方案是使用 cron 作业。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.