Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composer Autoloading

I'm currently trying to use PSR-0 autoloading with Composer, but I'm getting the following error:

Fatal error: Class 'Twitter\Twitter' not found

My directory structure looks like this

- Project
    - src
        - Twitter
            Twitter.php
    - vendor
    - Test
    index.php

My index.php file looks like this:

<?php

    use Twitter;
    $twitter = new Twitter();

My Twitter.php file looks like this

<?php 

namespace Twitter;

class Twitter
{
    public function __construct()
    {
        // Code Here
    }
}

And finally my composer.json looks like this:

{
"require": {
    "phpunit/phpunit": "3.8.*@dev",
    "guzzle/guzzle": "3.7.*@dev"
},
"minimum-stability": "dev",
"autoload": {
    "psr-0": {
        "Twitter" : "src/Twitter"
    }
}
}

I am getting a little confused. I come from a C# background and this way of working is kinda confusing me. What's the correct way to use PSR-0 autoloading?

like image 296
James Jeffery Avatar asked Nov 24 '13 21:11

James Jeffery


People also ask

What is autoloading in composer?

Autoloading: The classmap Directive You just need to provide a list of directories, and Composer will scan all the files in those directories. For each file, Composer will make a list of classes that are contained in that file, and whenever one of those classes is needed, Composer will autoload the corresponding file.

What is composer dump autoload?

composer dump-autoload. php artisan dump-autoload. It regenerates the list of all the classes that need to be included in the project (autoload_classmap. php). It will 'recompile' loads of files creating the huge bootstrap/compiled.php.

How do I get the composer json file?

To configure Composer for your PHP app json file specifies required packages. Verify that a composer. json file is present in the root of your git repository. Run composer install (on your local machine) to install the required packages and generate a composer.


2 Answers

In your composer.json use:

"autoload": {
    "psr-0": {
        "": "src/"
    }
}

or

"autoload": {
    "psr-0": {
        "Twitter\\": "src/"
    }
}

and then run php composer.phar dump-autoload

like image 199
Gianluca Mancini Avatar answered Sep 25 '22 12:09

Gianluca Mancini


Use

"psr-0": {
     "Twitter" : "src/"
 }

This instructs composer to create autoloader, that will look in src for everything from Twitter namespace. And since it is PSR-0, namespace is treated as a folder and added to declared path, so you should not include it in path part in composer.json

like image 36
dev-null-dweller Avatar answered Sep 23 '22 12:09

dev-null-dweller