Autoloading class with composer

Autoloading class with composer

You don’t use composer yet? Surely you’ve heard of the NPM repository – this is for JavaScript. There is also for PHP! There is no NPM in PHP, but there is composer. You can install it from getcomposer.org, it’s free! Completely free. Have you installed? Cool! Now let’s start generating composer.json. This is the file that collects all your packages. Start with:

// go to the template directory
composer init

You will generate composer.json with just such JSON

  "name": "kpiekarski/basic-project",
  "description": "WordPress Starter Theme",
  "authors": [
      "name": "Karol Piekarski",
      "email": "[email protected]",
      "homepage": "https://karolpiekarski.pl/",
      "role": "Web Developer"
  "require": {},
  "autoload": {}

The most important thing you need to know:

  1. require — packages that you download save here
  2. autoload — packages you download will be downloaded here
// standard file call

"autoload": {
  "psr-4": {
    "SiteManagement\\": "functions/SiteManagement"

Finally, we just need to run the autoload

require_once 'vendor/autoload.php';

new SiteManagement\SiteManagement();

Note that you now need to create a class in your functions/

You can search for packages here. It’s not everything! You can download public packages from github. All you have to do is do:

composer require name/package


composer require guzzlehttp/guzzle:^7.0
Posted in Bez kategorii