ilhan
ilhan

Reputation: 8945

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.

Upvotes: 6

Views: 296

Answers (2)

pinkal vansia
pinkal vansia

Reputation: 10300

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?

Upvotes: 7

Pᴇʜ
Pᴇʜ

Reputation: 57683

Your code goes into the root directory of your project (or any subdirectory). The vendor folder is only for packages/libraries downloaded by composer, you should never change anything in there.

To start a project just create a new file e.g. /my-project/index.php and require the autoload.php which is automatically created by composer:

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

    // here comes your project code

For more information about autoloading see the official composer documentation at Basic Usage: Autoloading

Upvotes: 0

Related Questions