3

I have a class called class.feed.php, how do I include it to Composer such that when 'vendor/autoload.php' is included or required in my for example index.php, the class will also be included?

Note, am still a PHP newbie.

halfer
  • 19,824
  • 17
  • 99
  • 186
W3Guy
  • 657
  • 1
  • 7
  • 16
  • Well .. you could start by not naming your class files as `class.foo.php`, because that's extremely shortsighted. Will you also use names `trait.bar.php` and `interface.buz.php`? How will your autoloader know that what you are loading is not a class but an interface? – tereško Apr 24 '14 at 15:49
  • Let's ignore the naming convention. assuming the class is called foo.php, how do i include it to composer such that when vendor/autoload.php is called, the class is also called? – W3Guy Apr 24 '14 at 15:55

1 Answers1

16

Here's an example of using composer.

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

Set the structure as follows:

 src/
   - AppName/
 vendor/
 composer.json
 index.php

place any classes inside the AppName folder, use a namespace for the class relative to src folder.

Classes should have the same filename as class name starting with a capital, for example a class called Demo in AppName:

<?php namespace AppName;

class Demo {

   public function __construct(){
    echo 'hi';
   }
}

Then in the root create index.php include the autoload from the vendor once composer has been installed.

To use any class call its namespace followed by the class name

<?php
require('vendor/autoload.php');

$demo = new \AppName\Demo();
Dave
  • 878
  • 8
  • 19