Reputation: 41
What is the logic behind composer autoloading? How does it map the namespace to a specific file and why do we always need to use the namespace of that class?
Upvotes: 1
Views: 1656
Reputation: 1695
- What is the logic behind composer autoloading?
- How does it map the namespace to a specific file?
- Why do we always need to use the namespace of that class?
Answers:
3. In many programming language namespace used to separate classes that have the same name, but different hierarchy - best example for this is Eloquent Builder and Query Builder. Well, think of it as some sort 'file path' like in your hard disk, you had let's say, file named b.txt
in directory dir-a
and dir-b
but they retains their own contents right? Anyway, it doesn't hurt to read the php documentation regarding namespace
(1, 2). Composer reads composer.json
to check which path represent a namespace and list every php files in it and store them into autoload_*.php
(if you ask me where the file located, it just inside your /vendor/composer/
everything with autoload
at the beginning of its name. Laravel - or rather Composer - knows how to load them and where they are located through these files. If you check the files you'll have an idea. The only convention in Composer's autoload that you need to remember is a single file only for a single class and it's class name should be exact same with file name (without php part - yes, this related to PSR-*
)
ps. correct me if i am wrong.
Upvotes: 2
Reputation: 45490
Let's assume you use autoload
alone this means it holds no scope (namespace
).
This means that if you ever install third party dependencies that classes with the same name in the vendor folder (most likely there will be), there will be a conflict that results into an error fatal to your applications.
Composer class autoload feature also conforms to PSR-4 Standards.
How does Composer map the files ?
This is specified in the composer.json
file, for example:
{
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
App
would be the namespace, and src
would be the folder
It is also useful for unit test, you can do the following just for development environment:
"autoload-dev":{
"psr-4" : {
"App\\Test\\": "tests/"
}
}
Upvotes: 1