Here is a simple example how to setup a simple autoloader with composer classmap.
1) install composer:
http://magento2-tuts.blogspot.de/2016/08/ubuntu-install-composer.html
2) create 2 classes in 2 folders.
- create a folder named "myproject"
- in this folder create a folder "app" and a folder "library"
- so that you have this structure:
--myproject
|__app
|__library
|__Calculator.php
In the app/library folder create a php Class "Calculator.php"
create autoloader
- in the "myproject" folder create a file "composer.json" with follwing content
Switch to your terminal to the folder, where your composer.json is stored. type:
php composer install
After that a "vendor" folder is generated with the autoloading files.
Every Classes which are stored in the classmap ("app/library") will be automaticly added to the autoloading classmap.
Create a file "index.php" in folder "myproject" and add folling content,:
You now can use the calculator class without require or include like that:
Switch to terminal and type:
php index.php
this will output the result of 2+2 in yout terminal. You see the class Calculator gets automaticly loaded.
Now lets add a new folder "models" to the classmap
- create a folder named "models" in the folder "myproject"
- create a php class "User.php" in that folder
Now add the new folder "models" to the composer.json classmap
- open composer.json and add "app/models" to the classmap, so that it looks like that:
- switch back to your terminal in the folder where composer.json is stored and type:
php composer dump-autoload
If you open vendor/autoload_classmap.php you will see the new addition of the Usermodel.
Thats it.
In one of the next tutorials, PSR 0 and PSR 4 will be explained.
Keine Kommentare:
Kommentar veröffentlichen