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

I am new to Composer, namespaces and startup, and I have not been able to figure out where to write my code (under vendor ?).

I created a directory named ilhan under vendor and a file called People.php . Then in the main index.php file using use ilhan\People.php as People; does not work, because I think it should have been written to autoload_namespaces.php initially.

But if I register ilhan as a provider, I think Composer will look into packagist.org, which is not there.

+6
source share
2 answers

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

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

Most likely, you already have psr-4 config autoload added to your composer.json file, if you use some kind of framework, in this case just add "Ilhan\\": "ilhan/" to it. Create People.php inside ilhan directory with the following contents

 <?php namespace Ilhan; class People{} 

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

Now in index.php only lower than require __DIR__.'/vendor/autoload.php'; should work

 use Ilhan\People; 

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

+7
source

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

To start a project, just create a new file, for example. /my-project/index.php and requires autoload.php , which is automatically created by the composer:

 <?php require __DIR__.'/vendor/autoload.php'; // here comes your project code 

For more information about startup, see the composer's official documentation for Primary Use: Startup

0
source

Source: https://habr.com/ru/post/989924/


All Articles