Dan Gravell
Dan Gravell

Reputation: 8240

Can't get Composer to load classes when using a file repository

I'm a PHP novice and just trying to create a package ("simple-php"), and then an example project ("example-php") that uses the package.

simple-php (the package)

simple-php has a composer file:

{
    "name": "simple/simple-php",
    "description": "",
    "version": "0.0.1",
    "autoload": {
        "psr-4": { "Simple\\" : "src/" }
    }
}

Inside simple-php is:

src/
  HelloWorld.php
composer.json

And HelloWorld.php is:

namespace Simple;

class HelloWorld
{
    public function __construct(
    )
}

example-php (the client of the package)

The file structure is:

index.php
composer.json

composer.json includes:

{
    "repositories": [
        {
            "type": "path",
            "url": "../simple-php"
        }
    ],
    "require": {
        "simple/simple-php": "0.0.1"
    }
}

I ran php composer.phar install on this and got, in composer.lock:

...
        {
            "name": "simple/simple-php",
            "version": "0.0.1",
            "dist": {
                "type": "path",
                "url": "../simple-php",
                "reference": "18171b07ac196fb22d8d95578be916e7897d003e"
            },
            "type": "library",
            "autoload": {
                "psr-4": {
                    "Simple\\": "src/"
                }
            },
            "transport-options": {
                "relative": true
            }
        },
...

So now in index.php I do:

...
require_once('vendor/autoload.php');
new Simple\HelloWorld();

vendor/autoload.php exists, btw, and it contains:

<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer/autoload_real.php';

return ComposerAutoloaderInit661a24b81ca7aae7b7471c810ee626fa::getLoader();

But when I run the page I get:

Fatal error: Uncaught Error: Class 'Simple\HelloWorld' not found in /var/www/html/index.php:21

I guess I'm not setting up some sort of namespace correctly, but I can't see it. How can I load the HelloWorld class?

I'm using the Docker php:7.2-apache image.

Upvotes: 1

Views: 154

Answers (1)

Dan Gravell
Dan Gravell

Reputation: 8240

The problem was: I was using the Docker image with Apache, and I wasn't providing the root folder containing example-php and simple-php.

Before I was inside the example-php folder and running:

docker run -d -p 9010:80 --name php-apache -v "$PWD":/var/www/html php:7.2-apache

The problem was the -v switch. I changed to:

docker run -d -p 9010:80 --name php-apache -v "$PWD/..":/var/www/html php:7.2-apache

(and then using the qualifier path of example-php when testing)

... and that fixed it.

Thanks to @turivishal for his help in debugging.

Upvotes: 1

Related Questions