3
votes

In my project inside the vendor directory I created a new directory named Hello and created a new class HelloWorld.php with the namespace Hello\Test. Then in the root of Hello I created a composer.json with default meta data (author, license, desc, required), and added autoload PSR-4 Hello\\Test\\.

So what do I need to do next to autoload my package. I looked at some Symfony components and their composer.json package and configuration is the same.

Is it possible to autoload my local package from vendor like this?

Dir structure:

|-my_project
|-composer.json
|---vendor
|-------composer
|-------autoload.php
|-------Hello
|-----------composer.json
|-----------HelloWorld.php

./vendor/Hello/composer.json

{
  "name": "Zend/Hello",
  "description": "My test package",
  "license": "MIT",
  "authors": [
    {
      "name": "Zend Zend",
      "email": "[email protected]"
    }
  ],
  "autoload": {
    "psr-4": {
      "Hello\\Test\\": ""
    }
  }
}

My HelloWorld.php class has namespace Hello\Test; Inside index.php i do include 'vendor/autoload.php And root composer.json

{
  "autoload": {
    "psr-4": {
      "": "src/",
      "Hello\\Test\\": "./vendor/Hello"
    }
  },
  "require": {
    "Hello/Test": "*"
  }

}

composer update

1
Have you tried running composer update ?awoyotoyin
Yup but nothing is happening. When i try to create instance in index.php where i include autload i get error class not found.Ivan
Ok then. Could you paste the psr-4 declaration in your composer.json? and your Hello directory structure?awoyotoyin
check now new updateIvan

1 Answers

4
votes

Okay! Sorry for the late reply. You only need one composer.json to make this work. The one in your main project directory.

Try using this:

{
   "name": "Zend/Hello",
   "description": "My test package",
   "license": "MIT",
   "authors": [
      {
          "name": "Zend Zend",
          "email": "[email protected]"
      }
   ],
   "autoload": {
       "psr-4": {
           "Hello\\Test\\": "vendor/Hello"
       }
   }
}

And your HelloWorld.php file should be like:

<?php

namespace Hello\Test;

class HelloWorld {

    // your methods goes here
}

Run a composer self update to get the latest composer the run composer update and it should now be added to your vendor/composer/autoload_psr4.php file