PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, January 31, 2022

[FIXED] Composer PSR-4 for application files

 January 31, 2022     autoload, composer-php, json, php     No comments   

Issue

I am new to using composer and have created a list of required projects in my composer.json file. I can use them within my index.php bootstrap file fine.

However I want to also be able to autoload my own project files outside of the vendor folder using composers autoloader. My folder structure is as follows:

vendor/
project/
   Project.php
index.php
composer.json

index.php

<?php

require 'vendor/autoload.php';

new \Project\Project;

Project.php

<?php

namespace Project;

class Project {
}

composer.json

{
    "autoload": {
        "psr-4": {
            "Project\\": "project"
        }
    }
}

This keeps coming up with the following error:

Fatal error: Class 'Product\Product' not found in index.php on line 5

What am i doing wrong? Or can I not use composers autoload to load my application files?

Edit Turns out I needed to run composer dump-auto -o to refresh the changes I made to the composer.json file. Credit to @Quasduck who posted in the comments.


Solution

Posting my comment as an answer

Whenever you tinker with the autoload section in your composer.json file, always make sure to update the autoloader after that by running

$ composer dump-autoload -o

This is also run automatically after each composer update or composer install.

Also notice the (optional, but recommended) -o param, which tells Composer to optimize the autoloads. This basically means that PSR-0/4 autoloads (like in your example) are converted to simple classmaps. This can speed up the autoloading significantly, especially in larger projects.

Updating the autloader can also solve issues when you update, rename or move a class but your application doesn't seem to pick up on that.



Answered By - Quasdunk
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing