5

I'm just getting started using composer for dependency management and I'm having a hard time figuring out how I'm not adhering to psr-4 for autoloading so I'm here for advice. I've got a class that generates random values that is already on the packagist. The project structure is the following (I've labeled the composer.json files A and B):

project dir

  |classfile.php 
A |composer.json
  |vendor
   |autoload.php
    |ejfrancis
      |php-random-value
B       |composer.json
        |RandomValue.php        <--the class I want autoloaded    

composer.json A

{
    "require": {
        "ejfrancis/php-random-value": "dev-master"
    }
}

composer.json B

{
    "name": "ejfrancis/php-random-value",
    "description": "Secure random value generator.",
    "require": {
        "php": ">=5.3.0"        
    },
    "license": "MIT",
    "autoload": {
        "psr-4": {
            "ejfrancis\\" : ""
        }
    }
}

and finally the RandomValue.php file, which declares the ejfrancis namespace

namespace ejfrancis;

class RandomValue{
  //foo
}

When I run the app I get an error 'class RandomValue not found', so it's not autoloading correctly. Am I not complying to psr-4, or is there something else I'm doing wrong? I've also tried autoloading just using a composer classmap like "classmap" : ["RandomValue.php"] to no success. Thanks for the help

Update: I've run 'composer validate' on the composer.json B file, it definitely is valid

ejfrancis
  • 2,925
  • 4
  • 26
  • 42
  • 1
    How does the code look like that creates that error you mention? As I see it, you most likely missed to use the correct namespace there, everything else looks good. – Sven Jun 25 '14 at 19:55
  • looks like you're correct! the code was '$randomValue = new RandomValue', I added 'use ejfrancis\RandomValue as RandomValue' at the top of the classfile it's being used in and now it works. if you add this as a full answer and not a comment, I'll mark it as correct – ejfrancis Jun 25 '14 at 20:29

2 Answers2

16

Change in your composer to "Namespace\\" and do a composer dump-autoload -o

reformed
  • 4,505
  • 11
  • 62
  • 88
Michal
  • 1,010
  • 2
  • 8
  • 18
  • I changed my autoload psr-4 attribute in composer.json B to "ejfrancis\\": "" and ran 'composer dump-autoload -o', still says class not found – ejfrancis Jun 24 '14 at 18:33
  • 1
    I've also run 'composer validate' on the composer.json B, it's definitely valid. you were correct about the trailing '\\' – ejfrancis Jun 25 '14 at 00:41
  • Thanks @ejfrancis for that composer command, it helped me see that my composer file was not formatted properly – Uriahs Victor Jul 11 '21 at 17:15
  • this saved m day although i was late to find it – Majd Mar 17 '22 at 15:21
2

I had a similar problem recently and after struggling for an hour, I found out that I haven't used the require_once 'vendor/autoload.php; in the project initial file.

I just sent this answer for whom forgot this part like me.

aminjabari
  • 21
  • 3