2

I am new to Php and composer, I want to access a Php class to another module using composer, This is my basic project structure (two modules common and 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

common/vendor/canvass/test.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"
}

worker/composer.json

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

worker/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();
?>

I am not able to do that with psr-0 or repositories either, is there any method to do this?

Aditya Kamat
  • 149
  • 1
  • 9

1 Answers1

2

What you are showing here is one project TestLocalRepository, which consists of two separate Composer projects, common and worker in the Source folder, each of them having a composer.json file and their own vendor folder. I think your project structure is not optimal.

From my point of view, you might place these two projects in the vendor folder of the main project and not inside the source folder. My suggestion would be to use one project TestLocalRepository and include both modules common and worker as dependencies of that project (in your composer.json).

You would get a structure like this:

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

Now: on a composer update, the dependencies common and worker would be fetched and placed into the vendor folder, then the autoloading would be generated. Then, in your src/index.php you would simply include require 'vendor/autoload.php'; and $t = new test/temocaller();;


If this is not what you want, then you can still, use the Composer Autoloader and add a custom location for classes to it. In your index.php: first require the autoloader then add the folder to autoload classes from, like so:

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

or just add the paths to the composer.json inside the TestLocalRepository.

Jens A. Koch
  • 39,862
  • 13
  • 113
  • 141