2

A while ago I created a twig extension. Recently I added a namespace so I could use it with composer more easily. I've done this a few times and it works fine with other files/classes.

The problem is that it only autoloads properly if I use the -o option (optimize) when I update or dumpautoload in composer.

So for example if I run composer dumpautoload -o my class is found with no issues. If I run composer dumpautoload it will NOT work and give me the following error:

Fatal error: Class 'Crecket\custom_twig_extension' not found in C:\Dropbox\Ampps\www\crecket.dev\index.php on line 24

My extension class:

namespace Crecket;

class custom_twig_extension extends \Twig_Extension{
    // The code
}

My composer file

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

Folder structure

src/custom_twig_extension.php

Does anyone know what is causing this? I can't seem to figure out what is causing this. I'm guessing it has to do with composer creating a classmap when I use optimize.

Crecket
  • 718
  • 2
  • 7
  • 24
  • It works fine for me with your setup. Check a couple things. Make sure you are requiring `vendor/autoload.php` from `index.php`. Also examine `vendor/composer/autoload_classmap.php` and `vendor/composer/autoload_psr4.php` after each command and see if that gives you any insights. – Justin Howard Jan 09 '16 at 02:00
  • @JustinHoward the class is visible in the psr4.php file but I checked in my index.php file using `get_declared_classes()` and it is not listed in there. I'm seriously clueless right now. I even tried adding/removing extra namespaces and changing folders – Crecket Jan 09 '16 at 17:38
  • I've got the same thing.. still not figured out why or how to fix it – Seb Aug 12 '16 at 21:42

1 Answers1

0

I was having a similar issue, which turned out to be because the class name in my file was different to the filename providing it. I had myclass.php and class MyClass { }

According to the reddit discussion about someone encountering a similar issue (https://www.reddit.com/r/laravel/comments/2zx3in/l5_composer_dumpautoload_gives_class_not_found/):

In PSR-4, you have to name the file the name of the class.

When I renamed myclass.php to MyClass.php the issue disappeared - double check you've used the same name (and case!) for both!

Seb
  • 6,507
  • 2
  • 19
  • 23