13 July 2018

配置

➜ composer config -g repo.packagist composer https://packagist.phpcomposer.com

全局变量

➜ export COMPOSER_HOME=/home/xxx/etc/php/composer
➜ export PATH=${PATH}:${COMPOSER_HOME}/vendor/bin

快速将项目部署为 autoload

➜ echo '{}' > composer.json
➜ composer install

➜ vi composer.json
{
  "autoload": {
    "psr-4": {
      "App\\": "src/"
    }
  }
}

➜ composer dump-autoload

autoload psr-4 classmap files

psr-4

{
  "autoload": {
    "psr-4": {
      "App\\": "src/"
    }
  }
}

index.php

require_once __DIR__ . '/vendor/autoload.php';

$obj = new App\Obj();
echo $obj->run();

src/Obj.php

namespace App;

class Obj {
    public function run() {
        echo 'ok' . PHP_EOL;
    }
}
➜ composer dump-autoload
➜ php index.php

classmap

classmap 的存在主要是为了兼容老项目没有 namespace ,另外(classmap 不支持通配符,如 ./src/*

{
  "autoload": {
    "classmap": ["src"]
  }
}

index.php

require_once __DIR__ . '/vendor/autoload.php';

$obj = new Obj();
echo $obj->run();

src/Obj.php

class Obj {
    public function run() {
        echo 'ok' . PHP_EOL;
    }
}
➜ composer dump-autoload
➜ php index.php

files

和 classmap 类似,不过 classmap 是相对目录来引用的,files 是相对文件来引用的

{
  "autoload": {
    "files": ["src/obj.php"]
  }
}

index.php

require_once __DIR__ . '/vendor/autoload.php';

$obj = new Obj();
echo $obj->run();

src/Obj.php

class Obj {
    public function run() {
        echo 'ok' . PHP_EOL;
    }
}
➜ composer dump-autoload
➜ php index.php

composer dump-autoload 和 composer dump-autoload -o

每次修改 autoload 里面的内容,都需要执行 composer dump-autoload 来生效。这个操作会更新 vendor/autoload.php 的内容,产生新的引用路径

composer dump-autoload -o 是当你的 composer.json 不需要更改了,这个操作会将 vendor/autoload.php 引用的 class 做一个优化操作(optimize)

error "conflict with your requirements or minimum-stability"

require 某个包错误 "but these conflict with your requirements or minimum-stability"
默认 composer 的 minimum-stability 是 stable,有些安装包需要用 dev 来运行

➜ vi composer.json
添加 "minimum-stability": "dev"

composer 安装 package 的时候指定 php 的版本

https://getcomposer.org/doc/06-config.md#platform

Example: {"php": "7.0.3", "ext-something": "4.0.3"}.
{
  "require": {
    ...
  },
  "config": {
    "platform": {
      "php": "7.0"
    }
  }
}