Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I write my code so that Composer can autoload my PHP classes?

I'm new to Composer, namespaces, and autoload and I wasn't able to figure out where to write my code (under vendor?).

I have created a directory named ilhan under the vendor, and a file named People.php. Then in the main index.php file using use ilhan\People.php as People; doesn't work because I think it must have been written in autoload_namespaces.php initially.

But if I register ilhan as a vendor then I think Composer will look into the packagist.org which it isn't there.

like image 778
ilhan Avatar asked Jun 29 '15 07:06

ilhan


1 Answers

Create ilhan inside root of your project directory, not in vendor directory and put following in your composer.json,

   "autoload": {                    
        "psr-4": {
            "Ilhan\\": "ilhan/"
        }               
    },

Most probably you already have psr-4 autoload config added in your composer.json file if you are using some sort of framework, in that case just add "Ilhan\\": "ilhan/" in to it. Now create People.php inside ilhan directory with following content

<?php

  namespace Ilhan;

  class People{}

Make sure require __DIR__.'/vendor/autoload.php'; is included in index.php any how, then run composer dump-autoload.

Now in index.php just bellow require __DIR__.'/vendor/autoload.php'; following should work,

use Ilhan\People;

But why do you want to use People class in index.php?

like image 187
pinkal vansia Avatar answered Oct 21 '22 02:10

pinkal vansia