Search code examples
phpvagranthomesteadpsr-4

Why I needed to recreate the composer autoloader inside the Homestead VM via ssh?


My project has the following file structure:

|- src
|-- PcMagas
|---- Dropbox.php
|---- DropBoxFactory.php
|- web
|-- index.php

And anything in the src folder is getting autoloaded as PSR-4 dictates via composer:

   "autoload": {
        "psr-4":{
            "": "src/"
        }
    }

A sample of a class Located in src/PCMagas is:

namespace PCMagas;

use \GuzzleHttp\Client; 
use PCMagas\Exceptions\FileNotFoundException;

class DropboxFactory
{
    public static function fomeFunc()
    {
       //Do stuff
    }
}

And On index.php I use the class like that:

require_once __DIR__ . '/../vendor/autoload.php';
use PCMagas\DropboxFactory;
DropboxFactory::fomeFunc();

Whilst Homestead's host I launch my app via:

composer dump-autoload -o
cd ^project_root^/web
php -S localhost:8990

The output of the commands are:

$ composer dump-autoload -o

No composer.json in current directory, do you want to use the one at /home/pcmagas/Kwdikas/php/apps/datawise? [Y,n]? Y
Generating optimized autoload files

And for the php -S localhost:8990 is:

PHP 7.0.33-0ubuntu0.16.04.3 Development Server started at Mon Apr 22 15:46:06 2019
Listening on http://localhost:8990
Document root is /home/pcmagas/Kwdikas/php/apps/datawise/web
Press Ctrl-C to quit.

And have no issues whatever. But when I try to launch via homestead I get the following error:

Fatal error: Uncaught Error: Class 'PCMagas\DropboxFactory' not found in /home/vagrant/code/web/index.php

Via doing:

vagrant ssh

And afterwards:

cd ~/code
composer dump-autoload -o

Worked like a charm, but still I have the following questions:

  1. Why on the host (outside of Homestead-running vm) the classes being autoloaded whilst inside is not? Is it because ./vendor folder is .gitignored?
  2. How I can automatically provision in order on Vm setup to autoload the PSR-4 namespaced classes? Does the after.sh run as root or as a the non-root user vagrant that in the /home/vagrant/code my application is located?

Solution

  • For question 2 you can find out the user via placing on your project's after.sh the following code:

    echo "I am user ${USER}"
    

    And run the command vagrant provision if the output is:

    I am user vagrant

    Then the following piece of code in after.sh should do the job:

    cd ~/code
    composer install
    composer dump-autoload -o
    cd
    

    For the first one I still have no answer to give you.