如何使用 Composer 从本地存储库加载 php 类


How to use Composer to load php classes from local repository?

我是 Php 和作曲家的新手,我想使用 composer 访问另一个模块的 Php 类,这是我的基本项目结构(两个模块通用和工人)索引.php

TestLocalRepository
--/Souce Files
    --/common
        --/vendor
            --/canvass
                --/test
                    --test.php
            --/composer
            --autoload.php
        --composer.json
    --/worker
        --/vendor
            --/composer
        composer.json
        temocaller.php
    --index.php

通用/供应商/画布/测试.php

<?php
namespace test;
class test {
    //put your code here
    function __construct() {
        echo "hello";
    }
}
?>

common/composer.json

{
    "name":"canvass/test",
    "type":"package",
    "version": "1.0.0"
}

工人/作曲家.json

{
    "autoload": {
        "psr-4": {
            "test":"../common/vendor/canvass"
        }
    }
}

工作人员/临时呼叫者.php

<?php
require_once dirname(__FILE__) . '../vendor/autoload.php';
use test;
class tempcaller {
    //put your code here    
    function __construct() {
        echo "tempcaller";
        $obj = new test();
    }
}
$t = new tempcaller();
?>

我也无法使用 psr-0 或存储库做到这一点,有什么方法可以做到这一点吗?

您在这里显示的是一个项目TestLocalRepository,它由两个单独的作曲家项目组成,commonworkerSource文件夹中,每个项目都有一个composer.json文件和他们自己的供应商文件夹。我认为您的项目结构不是最佳的。

从我的角度来看,您可以将这两个项目放在主项目的供应商文件夹中,而不是源文件夹中。我的建议是使用一个项目TestLocalRepository,并将模块commonworker作为该项目的依赖项(在您的composer.json中)包含在内。

你会得到这样的结构:

TestLocalRepository
- composer.json
+- src
   - index.php
+- vendor
    - autoload.php
    +- common           
    +- worker
       - temocaller.php

现在:在composer update上,将获取 common 和 worker 的依赖项并将其放入供应商文件夹中,然后生成自动加载。然后,在您的src/index.php中,您只需包括require 'vendor/autoload.php';$t = new test/temocaller();;


如果这不是您想要的,那么您仍然可以使用作曲家自动加载器,然后向其添加类的自定义位置。在你的索引中.php:首先需要自动加载器,然后添加文件夹以自动加载类,如下所示:

$loader = require 'vendor/autoload.php';
$loader->add('SomeWhere''Test''', __DIR__);

或者只是将路径添加到 TestLocalRepository 中的composer.json