6

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.

NikiC
  • 100,734
  • 37
  • 191
  • 225
ilhan
  • 8,700
  • 35
  • 117
  • 201

2 Answers2

7

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?

pinkal vansia
  • 10,240
  • 5
  • 49
  • 62
  • Thanks! It works exactly how I wanted! `People` class is only for testing purposes, I'll move it to another file. I use [Restler](https://github.com/Luracast/Restler). – ilhan Jun 29 '15 at 07:49
0

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

Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
  • I have `require_once '../vendor/restler.php';` which loads autoload.php and then it loads Restler and Illuminate\Database. But I want to load my own classes this way. – ilhan Jun 29 '15 at 07:39