Autoloading with Composer - Libbna/CUSTOM-CMS GitHub Wiki
-> The PHP Standard Recommendation is a PHP specification published by the PHP Framework Interop Group.
-
Files MUST use only <?php and <?= tags.
-
Files SHOULD either declare symbols (classes, functions, constants, etc.) or cause side-effects (e.g. generate output, change .ini settings, etc.) but SHOULD NOT do both.
-
Namespaces and classes MUST follow an "autoloading" PSR: [PSR-0, PSR-4].
-
Class names MUST be declared in StudlyCaps. ---> first letter of each work must be capital. e.g: StudlyCaps.
-
Class constants MUST be declared in all upper case with underscore separators. E.g:
namespace Vendor\Model;
`class Foo` `{` `const VERSION = '1.0';` `const DATE_APPROVED = '2012-06-01';` `}`
-
Method names MUST be declared in camelCase.
-> This PSR describes a specification for autoloading classes from file paths. It is fully interoperable, and can be used in addition to any other autoloading specification, including PSR-0. This PSR also describes where to place files that will be autoloaded according to the specification.
The term "class" refers to classes, interfaces, traits, and other similar structures. A fully qualified class name has the following form: ()*
Ref: https://www.php-fig.org/psr/psr-4/
So far our classes and function have all been floating around in our applications, available by just their names. In a complex project this can quickly become a problem, especially, if you have multiple classes that do similar things and have similar names. It can also lead to name collisions with third party code from libraries. Imagine you have a class called Address and some library also has a class with that name. How should PHP know which one to use?
To avoid name collision and to organize our code better, we can put classes and functions into namespaces:
<?php
//file name: src/MyProject/Foo/Derp.php
namespace "MyProject\Foo";
class Derp
{
//...
}
Namespaces are kind of like directories for your code and they usually directly map to actual file directories, like this MyProject\Foo\Derp class that lives inside the file src/MyProject/Foo/Derp.php. Even the syntax is similar, namespaces just use a \ as a separator instead of /.
- To install composer follow steps of this link, https://getcomposer.org/download/
- Composer init
- during the initialisation, it will ask if you want to install psr-4. Say YES. PSR-4 will be added to your composer.json file.
- https://getcomposer.org/doc/
- For manual setup of PSR-4, follow this link https://thewebtier.com/php/psr4-autoloading-php-files-using-composer/
- To check whether your classes are loading correctly or not run ~ composer -o dump-autoload
- After executing composer dump-autoload the autoloader will be generated on vendor/autoload.php.
- It just regenerates the list of all classes that need to be included in the project (autoload_classmap. php). Ideal for when you have a new class inside your project.