How to use composer autoload for the WordPress

  • 14.05.2021
  • 244
  • Read tyme: 5 min
  • Category:Dev

The article explains how to use Composer autoloading in WordPress to manage dependencies more efficiently. It outlines the setup process, including creating a composer.json file, installing packages, and integrating the autoloader into WordPress, improving code organization and performance.

How to use composer autoload for the WordPress

Where to start and why do you need it?

You need to install Composer locally, here’s a step-by-step guide on how to do it:

In the terminal run the command  

curl -sS https://getcomposer.org/installer -o composer-setup.php

sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer  

composer -v

If you saw this conclusion, then everything went well.

composer help

Large and medium plugins or themes always have a lot of files and classes that we need to include via require, require_once, or include.

As a result, we get a huge feed of file connections in function.php or in the main plugin file it looks like this

project before composer autoload

Six months later, when you open the project, if you did not leave comments in the code, then you no longer remember what the file is responsible for and where you need to make, for example, edits or fix a bug.

It is very inconvenient when adding new functionality to connect each time another file (main thing is not to forget to do this).

And here Composer comes to the rescue.

First step

Go to the root folder with your theme or plugin and create composer. json, it can be created in several ways

  1. We run the command in the composer init terminal and answer a few questions, Composer itself will generate a standard file
  2. Create manually

I choose the first option

{
    "name": "user/name_project",
    "authors": [
        {
            "name": "iWPdev",
            "email": "
        
            iw****@ou*****.com
            
                
                
                
            
            
                
                
                
            
        
"
        }
    ],
    "require": {
}
}

Next, we need to add the autoloading capability and the namespace of our classes, and a few more parameters for standardization.

{
  "name": "user/name_project",
  "description": "",
  "license": "GPL-2.0",
  "keywords": [],
  "homepage": "https://exemple.com/",
  "type": "wordpress-plugin", // If it's a plugin and wordpress-themes if it's a theme
  "authors": [
        {
            "name": "iWPdev",
            "email": "
        
            iw****@ou*****.com
            
                
                
                
            
            
                
                
                
            
        
"
        }
    ],
  "support": {
    "issues": "https://exemple.com/"
  },
  "config": {
    "platform": {
      "php": "7.2.5"
    }
  },
  "minimum-stability": "dev",
  "prefer-stable": true,
  "require": {},
  "autoload": {
    "psr-4": {
      "iWPdev\\": "includes/",
      "iWPdev\\Admin\\": " admin/",
    }
  }
}

We are interested in the code in bold, it makes it clear to Composer where to get our files.

A folder structure that looks like this:

Root project
	| ---- composer.json
	| ---- includes
		| ---- nameClass.php
	| ---- admin
		| ---- nameClass.php

I structure in my projects like this:

project tree

Second step

Execute the command in a terminal composer dump-autoload -o

dump-autoload

If you are working in PHPStorm, then it will be enough for you to click the button in the open file composer.json Install or Update

Third step

Now all we need to do is include one file in function.php or the main file of our plugin

require_once __DIR__ . '/vendor/autoload.php';

Now Composer does everything for us, it connects all files if it sees the initialization of a class in our code, and we always forget that we need to connect our files with classes by hand!

Related posts

Insights and Tips from My Journey

JWT Token Authentication in WordPress REST API

JWT Token Authentication in WordPress REST API

  • 17.11.2024
  • 35
Effective Ways to Prevent Email Spam on Your Website

Effective Ways to Prevent Email Spam on Your Website

  • 10.11.2024
  • 59
How to Send Contact Form 7 Submissions to a Telegram Bot

How to Send Contact Form 7 Submissions to a Telegram Bot

  • 05.11.2024
  • 104
All Posts

Ready to Take Your Project
to the Next Level?

Let’s bring your vision to life with expert development and custom solutions.
Contact us now and get started on transforming your ideas into reality!