In this article, we’ll discuss the basics of autoloading in PHP and how to autoload PHP classes with Composer. I'll explain why autoloading is so important and show you how to use Composer for autoloading step by step. I'll also explain the difference between the different kinds of autoloading in Composer.
Why Do We Need Autoloading?
When you build PHP applications, you may need to use third-party libraries. And as you know, if you want to use these libraries in your application, you need to include them in your source files by using require
or include
statements.
These require
or include
statements are fine as long as you’re developing small applications. But as your application grows, the list of require
or include
statements gets longer and longer, which is a bit annoying and difficult to maintain. The other problem with this approach is that you're loading the entire libraries in your application, including the parts you're not even using. This leads to a heavier memory footprint for your application.
To overcome this problem, it would be ideal to load classes only when they are actually needed. That's where autoloading comes in. Basically, when you use a class in your application, the autoloader checks if it’s already loaded, and if not, the autoloader loads the necessary class into memory. So the class is loaded on the fly where it’s needed—this is called autoloading. When you’re using autoloading, you don’t need to include all the library files manually; you just need to include the autoloader file which contains the logic of autoloading, and the necessary classes will be included dynamically.
Later in this article, we'll look at autoloading with Composer. But first, I'll explain how you can implement autoloading in PHP without Composer.
How Autoloading Works Without Composer
You might not realize it, but it is possible to implement autoloading in PHP without Composer. The spl_autoload_register()
function is what makes this possible. The spl_autoload_register()
function allows you to register functions that will be put into a queue to be triggered sequentially when PHP tries to load classes that are not loaded yet.
Let’s quickly go through the following example to understand how it works.
<?php function custom_autoloader($class) { include 'lib/' . $class . '.php'; } spl_autoload_register('custom_autoloader'); $objFooBar = new FooBar(); ?>
In the above example, we’ve registered the custom_autoloader()
function as our custom autoloader by using the spl_autoload_register()
function. Next, when you try to instantiate the FooBar
class and it’s not yet available, PHP will execute all the registered autoloader functions sequentially. And thus the custom_autoloader
function is called—it includes the necessary class file, and finally the object is instantiated. For this example, we're assuming the FooBar
class is defined in the lib/FooBar.php file.
Without autoloading, you would need to use the require
or include
statement to include the FooBar
class file. The autoloader implementation is pretty simple in the above example, but you could build on this by registering multiple autoloaders for different kinds of classes.
In practice, you won't often be writing your own autoloader, though. That's what Composer is for! In the next section, we’ll discuss how to use Composer for autoloading in PHP.
How Autoloading Works With Composer
Firstly, make sure to install Composer on your system if you want to follow along with the examples. When it comes to autoloading with Composer, there are different methods you could choose from.
Specifically, Composer provides four different methods for autoloading files:
- file autoloading
- classmap autoloading
- PSR-0 autoloading
- PSR-4 autoloading
As per the official Composer documentation, PSR-4 is the recommended way of autoloading, and we’ll go through that in detail in the next section. In this section, we’ll briefly discuss the other three options.
Before we go ahead, let’s quickly go through the steps that you need to perform when you want to use Composer autoloading.
- Define the composer.json file in the root of your project or library. It should contain directives based on the type of autoloading.
- Run the
composer dump-autoload
command to generate the necessary files that Composer will use for autoloading. - Include the
require 'vendor/autoload.php'
statement at the top of the file where you want to use autoloading.
Autoloading: The files
Directive
File autoloading works similarly to include
or require
statements that allow you to load entire source files. All the source files that are referenced with the files
directive will be loaded every time your application runs. This is useful for loading source files that do not use classes.
To use file autoloading, provide a list of files in the files
directive of the composer.json file, as shown in the following snippet.
{ "autoload": { "files": ["lib/Foo.php", "lib/Bar.php"] } }
As you can see, we can provide a list of files in the files
directive that we want to autoload with Composer. After you create the composer.json file in your project root with the above contents, you just need to run the composer dump-autoload
command to create the necessary autoloader files. These will be created under the vendor directory. Finally, you need to include the require 'vendor/autoload.php'
statement at the top of the file where you want to autoload files with Composer, as shown in the following snippet.
<?php require 'vendor/autoload.php'; // code which uses things declared in the "lib/Foo.php" or "lib/Bar.php" file ?>
The require 'vendor/autoload.php'
statement makes sure that the necessary files are loaded dynamically.
Autoloading: The classmap
Directive
Classmap autoloading is an improved version of file autoloading. You just need to provide a list of directories, and Composer will scan all the files in those directories. For each file, Composer will make a list of classes that are contained in that file, and whenever one of those classes is needed, Composer will autoload the corresponding file.
Let’s quickly revise the composer.json file to demonstrate the classmap autoloader.
{ "autoload": { "classmap": ["lib"] } }
Run the composer dump-autoload
command, and Composer will read the files in the lib directory to create a map of classes that can be autoloaded.
Autoloading: PSR-0
PSR-0 is a standard recommended by the PHP-FIG group for autoloading. In the PSR-0 standard, you must use namespaces to define your libraries. The fully qualified class name must reflect the \<Vendor Name>\(<Namespace>\)*<Class Name>
structure. Also, your classes must be saved in files that follow the same directory structure as that of the namespaces.
Let’s have a look at the following composer.json
file.
{ "autoload": { "psr-0": { "Tutsplus\\Library": "src" } } }
In PSR-0 autoloading, you need to map namespaces to directories. In the above example, we’re telling Composer that anything which starts with the Tutsplus\Library
namespace should be available in the src\Tutsplus\Library directory.
For example, if you want to define the Foo
class in the src\Tutsplus\Library directory, you need to create the src\Tutsplus\Library\Foo.php file as shown in the following snippet:
<?php namespace Tutsplus\Library; class Foo { //... } ?>
As you can see, this class is defined in the Tutsplus\Library
namespace. Also, the file name corresponds to the class name. Let’s quickly see how you could autoload the Foo
class.
<?php require 'vendor/autoload.php'; $objFoo = new Tutsplus\Library\Foo(); ?>
Composer will autoload the Foo
class from the src\Tutsplus\Library directory.
So that was a brief explanation of file, classmap, and PSR-0 autoloading in Composer. In the next section, we’ll see how PSR-4 autoloading works.
How PSR-4 Autoloading Works With Composer
In the previous section, we discussed how PSR-0 autoloading works. PSR-4 is similar to PSR-0 autoloading in that you need to use namespaces, but you don’t need to mimic the directory structure with namespaces.
In PSR-0 autoloading, you must map namespaces to the directory structure. As we discussed in the previous section, if you want to autoload the Tutsplus\Library\Foo
class, it must be located at src\Tutsplus\Library\Foo.php. In PSR-4 autoloading, you can shorten the directory structure, which results in a much simpler directory structure compared to PSR-0 autoloading.
We’ll revise the example above—see if you can spot the differences.
Here's what the composer.json file looks with PSR-4 autoloading.
{ "autoload": { "psr-4": { "Tutsplus\\Library\\": "src" } } }
It’s important to note that we’ve added trailing backslashes at the end of namespaces. The above mapping tells Composer that anything which starts with the Tutsplus\Library
namespace should be available in the src directory. So you don’t need to create the Tutsplus and Library directories. For example, if you request the Tutsplus\Library\Foo
class, Composer will try to load the src\Foo.php file.
It’s important to understand that the Foo
class is still defined under the Tutsplus\Library
namespace; it’s just that you don’t need to create directories that mimic the namespaces. The src\Foo.php file contents will be identical to those of the src\Tutsplus\Library\Foo.php file in the previous section.
As you can see, PSR-4 results in a much simpler directory structure, since you can omit creating nested directories while still using full namespaces.
PSR-4 is the recommended way of autoloading, and it’s widely accepted in the PHP community. You should start using it in your applications if you haven’t done so already!
Conclusion
Today, we discussed autoloading in PHP. Starting with the introduction of different kinds of Composer autoloading techniques, we discussed PSR-0 and PSR-4 autoloading standards in detail in the latter half of the article.
Learn PHP With a Free Online Course
If you want to learn PHP, check out our free online course on PHP fundamentals!
In this course, you'll learn the fundamentals of PHP programming. You'll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you'll build up to coding classes for simple object-oriented programming (OOP).
Along the way, you'll learn all the most important skills for writing apps for the web: you'll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.
-
FREEPHPPHP Fundamentals
No comments:
Post a Comment