2

我是 Php 和 Composer 的新手,我想使用 Composer 将 Php 类访问到另一个模块,这是我的基本项目结构(两个模块 common 和 worker)index.php

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

常见/供应商/画布/test.php

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

普通/作曲家.json

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

工人/作曲家.json

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

工人/tempcaller.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 或存储库来做到这一点,有什么方法可以做到这一点吗?

4

1 回答 1

2

您在这里展示的是一个项目TestLocalRepository,它由两个独立的 Composer 项目组成,commonworker文件Source夹中,每个项目都有一个 composer.json 文件和它们自己的供应商文件夹。我认为您的项目结构不是最佳的。

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

你会得到这样的结构:

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

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


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

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

或者只是将路径添加到composer.jsonTestLocalRepository 内部。

于 2015-02-02T18:00:33.570 回答