Composer autoload

I am currently trying to use PSR-0 autoload with Composer, but I am 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'm a little confused. I am coming from a C # background and this way of working confuses me. What is the correct way to use PSR-0 autoload?

+9


source to share


5 answers


In your composer .json use:

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

      

or



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

      

and then run php composer.phar dump-autoload

+10


source


Using

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

      



This instructs the composer to create an autoloader that will look like src

for the entire namespace Twitter

. And since it is PSR-0

, the namespace is treated as a folder and added to the declared path, so you should not include it in the path part incomposer.json

+3


source


First of all,

My index.php file looks like this:

use Twitter;
$twitter = new Twitter();

      

If this is your index.php, you forgot to enable the composer script autoloading first.

require __DIR__ . '/vendor/autoload.php';

      

See https://getcomposer.org/doc/01-basic-usage.md#autoloading for details .

+2


source


There is an error in your index.php: use Twitter\Twitter; $twitter = new Twitter();

or $twitter = new Twitter\Twitter();

+1


source


This is a very late answer, but the first thing to do for "autoloading" is PHP 5.6 or higher.

0


source







All Articles