Search code examples
phplaravelcomposer-phppackagist

Loading a composer class in laravel


I'm in the process of trying to make a laravel compatible composer/packagist package. I'm using Laravel 5.5.

I've created a package : floor9design/machine-identifier. Composer downloads this to vendors/floor9design fine, but despite reading/googling how to do this, I'm unsure of how to include this in my laravel projects.

PHP Storm is correctly picking up the class, auto-completing as expecting.

I have not modified any files so far. If I add the following to a controller:

use Floor9design\MachineIdentifier\MachineIdentifier;

(alongside some class usage on the page).

PHP storm autocompletes this (as it does with other classes validly called).

When I try to load this, the following error comes:

Class 'Floor9design\MachineIdentifier\MachineIdentifier' not found

I've had a look round plenty of tutorials, and this final step seems to be missing from a lot of information.

I realise there are three approaches:

Firstly: Direct include_once, which while working, is not the normal approach

Secondly: Pre-laravel 5.5 approach (add something to app.php)

Thirdly Laravel 5.5 approach and up, autodetection of something.

I've deliberately said something as the documentation seems to speak about ServiceProviders, and I simply don't get how they work.

Let me rephrase this into a question and a follow up question:

Question: apart from include_once, how do I load the MachineIdentifer class from floor9design/machine-identifier in Laravel.

Question 2: If the answer is via a service provider, can you simply explain how they relate to one another.

Thanks

Answer (as accepted below)

On the composer repo I was incorrectly specifying the PSR4 namespace, which is now corrected to:

    "autoload": {
    "psr-4": {
        "Floor9design\\MachineIdentifier\\": "src"
    }
}

The previous namespace had a -, which is an illegal character. Many thanks to lawrence-cherone.


Solution

  • Your PSR4 is wrong in the package

    floor9design\\machine-identifier\\": "src"

    Will cause the composer/autoload_psr4.php to map to:

    'floor9design\\machine-identifier\\' => array($vendorDir . '/floor9design/machine-identifier/src'),
    

    Which is not a valid class namespace.

    You should change the PSR4 to match your class namespace:

    Floor9design\\MachineIdentifier\\": "src"

    Once you fix that you will be able to use it like normal from anywhere in your project.