I am a newb to Composer and how best use it.
I have a library I am bringing up to date by introducing Namespaces and replacing all cURL calls by using the PHP Request lib Guzzle.
Here is my composer.json
{
"description": "Description",
"require": {
"php": ">=5.3.0",
"guzzlehttp/guzzle": "~6.0"
},
"autoload": {
"psr-4": {
"MyClass\\": "src/"
}
}
}
Inside of src/MyClass/API.php
, I have this
namespace MyClass;
require_once(dirname(dirname( dirname( __FILE__ ) )).'/vendor/autoload.php');
use MyClass\Exceptions\MissingAccountId;
use MyClass\Exceptions\MissingAuth;
use MyClass\Exceptions\InvalidResponse;
use GuzzleHttp\Client;
Why do I need to explicitly require autoload.php
? Im a little confused about setting things up, so my apologies for the newb questions (I've been away from PHP programming for almost 4.5 years).
If I don't require autoload.php
, then I receive an error of PHP Fatal error: Class 'GuzzleHttp\Client' not found
It's exactly what it says. It autoloads the needed libraries as needed. This is needed, rather than doing a manual require
for each needed libraries (which is usually done in the old way). The autoload.php file, automatically determines which classes is needed, and require
the files to be loaded. This have the advantage of not needed to care about doing it manually and also reduce startup time since only the needed libraries are required.
Even I am learning about Composer too, what I have recently learned is, Composer is used to:
Before in the project/application we used to require
or autoload
each library, which was little hectic and not neat to manage the PHP libraries. So the composer.
Composer generate the autoloader file for you to include in your project. So coming to your question, you are configuring the composer.json(telling composer) to include the class MyClass
in composer's autoloader.
Reference: https://getcomposer.org/doc/01-basic-usage.md#autoloading
If the vendor directory is fully managed by composer(which I prefer), mean no other library is installed manually. Then you don't need to push it to your repository(i.e you can add .gitignore).
PS: I have just tried to explain what I have understood till now about composer. Please feel free to correct or add to my answer. Even I am learning.