I've just started to work with Composer, but I can't really grasp how I should solve the following issue: how do I set up so I don't have to state \Other\ when using a class? (i.e. so my custom classes works like the Mustache classes)
This works
$mustache = new Mustache_Engine();
$foo = new \Other\SimpleClass();
This does not work
$foo = new SimpleClass();
composer.json
{
"autoload": {
"psr-0": {
"Other": "lib/",
"Mustache": "lib/"
}
}
}
Folder structure
/lib
/Mustache
/Other
I have entered namespace Other;
in all files in my Other-folder
how do I set up so I don't have to state \Other\ when using a class?
Don't strive for not using namespaces.
Not using namespaces makes only sense for really small scripts, which run standalone and don't reuse pieces of code from other vendors (components/libraries).
I still don't understand why
$mustache = new Mustache_Engine();
doesn't have to be$mustache = new \Mustache\Mustache_Engine();
Mustache_Engine
is not namespaced (yet).
They use a string-prefix-namespace: they simply add Mustache_
to the classname Engine
to avoid class name collision with other classes called Engine
. This code will run on old and newer PHP versions.
Eventually, it will be come \Mustache\Engine
, when the Mustache developers update the code to make use of namespaces. This code will only run on PHP versions, which support namespaces as a language feature.
Autoloading of Mustache
If you installed Mustache using Composer
{
"require": {
"mustache/mustache": "^2.9"
}
}
then Composer will generate the autoloading for Mustache automatically.
You don't have to add a PSR-0 directive to composer.json
to get it working.
You only need to set PSR-0, if you downloaded and extracted Mustache manually into the /lib
folder. This is the old way of working with dependencies - leverage Composer instead.