- Autoload classes in WordPress with PHP and Composer
- But wait, what is object-oriented programming?
- Getting back to autoloading
- Calling classes in WordPress without autoloading
- Calling classes in WordPress with autoloading
- Different standards of autoloading
- How to set-up WordPress autoloading
- WordPress Autoload Classes and WordPress Naming Conventions
- Autoloading and composer
- Done! Questions?
- Использование PHP-классов при написании плагинов
- Как создать PHP-класс
- Что такое область видимости метода и свойства?
Autoload classes in WordPress with PHP and Composer
If you are developing plugins or themes for WordPress, the chances are big you are using Classes to format your code, especially if you have more experience with development and object-oriented programming (OOP). And did you know that in WordPress, autoloading classes with PHP is possible? With autoloading, classes are automatically loaded when they are called. Pretty useful, if you ask me.
But wait, what is object-oriented programming?
But wait, you are going way to fast! I just started developing. So what on earth is object-oriented programming?
In essence, object-oriented programming revolves around the use of so-called objects. Objects can have certain data attached to them. In PHP, this is in the form of properties. Additionally, objects can have certain functions, called methods. Often, these methods are used to manipulate properties.
In programming, an object is often represented by a class. Let’s give an example in PHP.
property = 1; > public function getProperty() < return $this->property; > > $class = new Someclass(); // Constructs the class echo $class->getProperty(); // Echoes 1
So in the above example, we have a class called Someclass with a property called $property and the method getProperty. Properties within a class are accessed by using $this->property.
By initiating the $class using new Someclass, we are constructing a new object from this class. We then can access this object methods and properties as long as they are public.
Now if you really like this, there is a Canadian fellow named Carl Alexander who is writing a lot about object-oriented programming. You may want to read this introduction to object-oriented programming for WordPress.
Also, if you’re kind of new to PHP, I would recommend checking out this introduction to PHP, which will learn you all the basics step by step.
Getting back to autoloading
But that’s enough of the introduction! Let’s get back to the actual topic of autoloading.
Now PHP comes with a very useful function called autoloading. What it basically means is that every time when you call a class, it is automatically loaded. This is particulary useful if you have to include many libraries or scripts.
Calling classes in WordPress without autoloading
Without autoloading, you have to require or include every class manually as shown the example below. Obviously, if you are using a lot of classes, you require a lot of include statements.
Calling classes in WordPress with autoloading
With autoloading, you can just call the class and it will load. Providing you have set it up correctly, of course. The following code would automatically include the given class and execute it if you would have been using autoloading.
For the above example to work correctly, the class should be properly namespaced and placed in the right directory. Namespacing is a PHP utility that indicates to what namespace a given class (and file) belongs. A namespace often matches the build-up of a directory.
So, in the above example, the new Folder\someclass would be placed in folder/someclass.php. The given class would then start with indicating the namespace using PHP namespaces. In this case, Folder.
So what about classes that are placed in directories with multiple folders? It’s quite easy: just namespace according to the folder structure. For example, use namespace Folder\Subfolder.
Different standards of autoloading
If you have been looking into autoloading, you may have seen terms such as PSR-0 and PSR-4 before. Now, these terms indicate the standard for how to deal with file paths and namespacing. In other words, how should namespaces and folders be structured accordingly?
The current standard is PSR-4, so luckily we only have to dive into this standard. So what does PSR-4 entail? Let’s look at our previous example:
- If we call the class, we use the namespace and class: new Folder/ Someclass ()
- This logic resembles the folder structure, namely folder/someclass.php
- In someclass.php, we use namespace Folder in our first rule of coding to indicate to what namespace it belongs.
In a very basic form, PSR-4 is about this: the namespace of a class follows the path (in other words, the folders or directories) in which a given class is placed. There are some additional rules which you may inspect here.
How to set-up WordPress autoloading
So how can you enable WordPress class autoloading? PHP comes with a handy function called spl_autoload_register which is used to register new functions for autoloading classes. Let’s look at a basic example. We assume this file is placed in the functions.php file of our WordPress theme.
So what does the above example do?
- Whenever a class with $classname is called (for example, Folder/ Someclass ), it will lowercase this class and separate any backward slash for the slash that is used to separate directories.
- Subsequently, it adds the classes folder and any higher directories in front of this class resulting in $classpath. In this example, $classpath can be something like wp-content/themes/theme/classes/folder/someclass.php
If we would have added our previous class Someclass within classes/folder/someclass.php in your theme, we can now call new Folder\Someclass(); without manually including it!
WordPress Autoload Classes and WordPress Naming Conventions
Now as you may have noticed, we so far ignored the WordPress naming conventions for classes. For PHP classes, WordPress dictates to use the class prefix before the filename. So in our example, we end up with folder/class- someclass .php.
So how can we adjust our existing autoloader to comply with the standards of WordPress? We have to split up our namespaced folder structure and add the class- prefix to the actual file. It’s quite easy using PHP’s explode function:
Autoloading and composer
The real power of using autoloading is making use of modules from C omposer.
For example, we have written various scripts for WordPress such as the WP Custom Fields script and the WP Components script. Using Composer, these can easily be included within a theme or plugin.
In the following example, we assume a new theme is developed. Within the root folder of the theme, we place a file called composer.json. It may look like this:
< "name": "makeitworkpress/autoloading-demo", "description": "Demo for autoloading with WordPress", "repositories": [ < "type": "vcs", "url": "https://github.com/makeitworkpress/wp-components.git" >], "require": < "php": ">=7.0", "makeitworkpress/wp-components": "dev-master" >, "homepage": "https://github.com/makeitworkpress/wordpress-autoload-class/" >
This file indicates it is going to use a custom repository from GitHub. Obviously, you need to use Composer’s update command from our terminal.
- If you haven’t been using composer, you have to install it first.
- Go to your terminal, and make sure you are in the right location (for example, the folder of the theme you’re developing).
- Type composer update –prefer dist. Composer will now load the required modules in a folder named vendor. Because you are using composer update –prefer-dist, it will only load the distribution version of the repository and not all .git related code.
- Composer will also automatically set-up some scripts for autoloading ..
Our module has been imported! The next you want to do is to require and execute the autoloading script that has been included by C omposer. So just add the following line to your functions.php:
/** * Uses composer to autoload our vendor modules. * Make sure you are using composer update --prefer dist in your terminal first, so these modules are loaded! */ require_once 'vendor/autoload.php'; /** * This loads the WP Components module, as it is included in the example. */ $components = new MakeitWorkPress\WP_Components\Boot();
It’s that easy. The vendor modules now only need to be called and are automatically loaded.
Done! Questions?
Alas! You have harnessed the power of class autoloading in WordPress. Feel free to leave any comments or questions below. There is also a complete overview of the code from this article available on GitHub.
Использование PHP-классов при написании плагинов
В этом видеоуроке мы полностью перепишем наш плагин на PHP-класс. Да, до этого мы делали его на обычных функциях.
Это не значит, что любой плагин необходимо писать, используя PHP-классы, вполне возможно, что ваш плагин, состоящий из 5 хуков может вполне прекрасно себя чувствовать на функциях.
Чтобы скачать плагин, который получился в процессе этого урока, нужно купить курс.
Как создать PHP-класс
// не забываем проверять существование класса if( ! class_exists( 'trueMinMaxQty' ) ) { class trueMinMaxQty { // метод-конструктор, который выполнится при инициализации класса public function __construct() { } } // инициализируем класс / создаём объект класса new trueMinMaxQty(); }
Что такое область видимости метода и свойства?
class trueMinMaxQty { // публичный метод-конструктор public function __construct() { } // публичный метод public function MyPublic() { } // защищённый метод protected function MyProtected() { } // приватный метод private function MyPrivate() { } // если не указано, то метод тоже публичный function Foo() { $this->MyPublic(); $this->MyProtected(); $this->MyPrivate(); } } $myclass = new trueMinMaxQty; $myclass->MyPublic(); // ОК $myclass->MyProtected(); // Фатальная ошибка $myclass->MyPrivate(); // Фатальная ошибка $myclass->Foo(); // Все методы отрабатывают норм
- 11 видеоуроков
- Можно скачать готовый код после каждого урока
- Можно начать проходить курс сразу же после оплаты
- Единоразовый платёж
- Доступ навсегда
- Уроки актуальны в 2023-м году