1

I have created a simple package on packagist for learning (tommytest/tommytest). It installs fine, but I have to run "composer dump-autoload -o" immediately after it is installed. Before manually running the dump-autoload I get this:

Fatal error: Class 'mysqlgridspace\Page' not found in C:\xampp\htdocs\simple\index.php on line 5

After manually running dump-autoload it works fine. Isn't it supposed to handle the autoload set-up automatically when the package is installed?

Here's my composer.json (located in: simple/vendor/tommytest/tommytest/composer.json)

 {
  "name": "tommytest/tommytest",
  "type": "library",
  "description": "Framework agnostic data grid",
  "keywords": ["datagrid","data grid"],
  "homepage": "https://github.com/escalibore/tommytest",
  "license": "MIT",
  "authors": [
    {
      "name": "Tommy Bert",
      "email": "tom@tberthold.com",
      "homepage": "http://tberthold.com",
      "role": "Developer"
    }
  ],
  "require": {
    "php": ">=5.3.0"
  },
  "autoload": {
    "psr-4": {
      "mysqlgridspace\\":"src/"
    }
  }
}

And my class file (located in: simple/vendor/tommytest/tommytest/src/Mysqlgridmain.class.php)

<?php
namespace mysqlgridspace;

class Page {
    public function __construct()
    {
        echo "hello, i am a page.<br>";
    }
}

class Book {
    public function __construct()
    {
    echo "hello, i am a book.<br>";
    }
}

2 Answers2

2

Those classes cannot be autoloaded with Composer's PSR-4 autoloader because it resolves the class name mysqlgridspace\Page to a file named Page.php, which should exist in src - it doesn't, though.

First of all, there should only be one class declared in each file.

You should have

src/
    Book.php
    Page.php

each declaring one class only.

Then your PSR-4 autoloading should work.

For reference, see http://www.php-fig.org/psr/psr-4/.

localheinz
  • 9,179
  • 2
  • 33
  • 44
  • Thanks @localheinz, putting each class in it's own file of the same name worked, and this gives me a better understanding of how psr-4 autoaloding works. Thanks for solving the mystery! – Tom Berthold Dec 26 '15 at 18:45
1

I found a way around the problem. I added "files": ["src/Mysqlgridmain.class.php"], to the autoload details in my composer.json

So it went from:

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

to:

"autoload": {
  "files": ["src/Mysqlgridmain.class.php"],
  "psr-4": {
    "mysqlgridspace\\":"src/"
} 

I don't know why the psr-4 tag doesn't do it, but I think this is an acceptable work-around.

  • 1
    It might be, that Composers class scanner isn't picking it up, because of the `.class.php` extension. You could rename the file from `Mysqlgridmain.class.php` to `MysqlGridMain.php` and re-try. – Jens A. Koch Dec 21 '15 at 23:56