4 February

PHP Best Practices to Follow in 2020

Website developmentPHPDevelopment of mobile applicationsDevelopment for e-commerceSoftware


Web development trends seem to be heading more towards server-side scripting languages over client-side scripting languages. And it can be difficult to decide where to start and what to choose.

This year W3techs.com, a web technology survey portal, released a list of the five most in-demand server-side programming languages for web development.

Here is the list:

  • PHP
  • Java
  • ASP.net
  • Ruby
  • Static files

The majority of sites are built on PHP (approx. 78.9%), but some of them are made in ASP.net (10.6%), Java (3.7%), Python (1.3%), Ruby (3%) or just in JavaScript (0.8% — however, these don't have a database).

Clearly, PHP holds the majority. So let's learn more about it.

PHP was developed with built-in web development capabilities. The new language features included in PHP 7.4 make it easier for programmers to enhance the speed of their web applications significantly without deploying additional resources.

Unfortunately, PHP version 5.6, 7.0, and 7.1 are no longer officially supported. But approximately 64% of WordPress sites are still running on those outdated versions.

The good news? Programmers can switch to the most recent version of this widely used server-side scripting language to improve the load speed of their websites without putting in too much extra time and effort.

How I Approached Modern PHP Development


When I first started learning PHP I was using Joomla. Then I moved to open source frameworks with PHP version 4. I was especially interested in the open-source framework Symfony, which has improved the PHP ecosystem drastically. I also became more interested in PHP version 7.1 in particular while working on an e-CMS project (PIMCore version 5.8.6) which was quite challenging.

On top of that, it’s a very stressful task, since the core management team expect a lot from you for the task on an open-source project. Back then, PHP version 7.1 is the latest version and is more efficient than version 5 and can deliver a huge performance up to 4X faster than older versions.

A faster website built on PIMCore version 5.8.6 and version PHP 7.1 will be rewarded by search engines. I have used it, so Syncrasy Tech PIM Solution Provider site will rank higher in search!

Let's dive into PHP best practices and the advantages of upgrading to the newest PHP version 7.4.

PHP Best Practices To Follow in 2020


1. Always Use PSR- 12 recommendations For Error-Free Coding


I have always used PSR-12 (PHP Standard Recommendations) instead of the WordPress coding standard. It is one of the most substantial standards that is also used by the PHP frameworks Symfony and Laravel. It covers everything from parentheses to control structures, methods, indentation, line length, and coding rules about how many gaps a programmer can leave between different code structures.
This is mainly because WordPress standards are obsolete and don't support any of the newer language features. Using modern PHP PSR-2 features is also a good practice.

2. Make Your Code Concise and Readable With the Twig Template


Twig is the best example of a PHP template engine. It is used by Symfony. In Twig, the code is more concise and readable, and it supports output escaping and template extension using inheritance and blocks. Twig is also great performance-wise, as it compiles to PHP templates and has no overhead. It is limited to templating only. It allows you to remove business logic from templates and enforces separation of concerns.

It’s really easy to learn for developers because Twig doesn’t have many functions, and the base code is HTML. So if you know HTML, you just need a few more functions and you’re good to go with Twig template.

Twig has a clever mechanism of template assembly. It compiles templates into simple PHP classes and stores the result in the cache files. Thus, Twig does not parse templates twice.

Twig is so flexible that it can easily be extended according to your choice. It allows you to edit the tags, use parentheses instead of curly braces, redefine the class, add a new filter, function, or test, etc.

Below is an example of coding in the Twig Template:

foreach ( $options as $option ) {
    ?>
    <tr class="form-field">
        <th scope="row">
            <label for="<?php echo esc_attr( $option->option_name ); ?>">
                <?php echo esc_html( strtolower( $option->option_name ) ); ?>
            </label>
        </th>
    </tr>
    <?php
} // End foreach


‌{% for option in options %}
    <tr class="form-field">
        <th scope="row">
            <label for="{{ option.option_name }}">
                {{ option.option_name }}
            </label>
        </th>
    </tr>
{% endfor %}

3. Composer Acts As a Dependency Manager


A composer is a tool that allows you to declare libraries in a project that you are using. It is a dependency manager for PHP that automates downloads, installations, and updates. You need to include the Composer’s autoload file vendor/autoload.php for each library.

It is important to use dependency management to avoid conflicts at the application level. WordPress plugins and themes don’t use third-party libraries because of the extensive API that fills almost any need.

Let's think about it this way: suppose two plugins require the same PHP library but they're using different versions of it.

The plugin that runs first gets the correct version – but the second plugin also gets that same version. This possibly creates conflicts at the application level. Composer is the only solution that doesn't create conflicts when using third-party libraries.

4. Use 'Namespaces' To Avoid Name Collision


WordPress uses a global namespace. This means that any classes or functions declared globally are visible anywhere in the whole codebase. Naming conflicts lead to errors, and we don't want that.
For example, naming collisions happen when you declare a function with a name that already exists. So instead of using simple Class names like Order, I can make it something like:

Syncrasy_Get_My_Plugin_Order

where “Syncrasy” is the unique prefix that I just made up.

Namespaces help to organize code and avoid name collision. You can also use complex namespaces, for example, those separated with a slash.

My example
class Syncrasy_Get_My_Plugin_Order

would be Syncrasy\_Plugin\Order if done using namespaces. Here syncrasy and Get_My_Plugin are sub-namespaces and Order is the class name. You can add a use statement and use only the class name afterward.

See how it looks:
use Syncrasy\Get_My_Plugin\Order;

$a = new Order;

5. Always Use the Autoloader Function in PHP


In my development project, most PHP workflows form by using require or include statements. But I need to add more require statements in the main plugin file.

An autoloader is a function that automatically includes files and does so only when needed. The main benefit is there is no need to add any require statements manually anymore.

With an autoloader function, you know in which file your classes and functions live. For that, you can work on the PHP-FIG and PSR-4 autoloader tool.

An example class
Syncrasy\GetMyPlugin\Models\Order
would need the folder structure below:


/get-my-plugin
    get-my-plugin.php
    /includes
        /Models
            Order.php

6. Use Arrow Functions For Better & Cleaner One-Liner Functions


Functions in PHP tend to be lengthy, even when performing simple operations. This is due to a large amount of syntactic boilerplate, and because you need to manually import used variables. This makes PHP code that uses simple closures confusing to read and even harder to understand.

If you use arrow function syntax, you can have a variety of functions such as variadics, default values, parameter and return types, as well as by-reference passing and returning. All while maintaining clean, readable code.

Below is an example of Arrow Function Syntax in PHP 7.4:

array_map(function (User $user) { 
    return $user->id; 
}, $users)
PHP 7.4 allow you write this code in this way:

array_map(fn (User $user) => $user->id, $users)

7. Foreign Function Interface: a Simple Way to Call Native Functions


One of the best and most long-awaited features of PHP 7.4 is FFI (Foreign Function Interface) support.
PHP 7.4 FFI comes along with TLS 1.3 (Transport Layer Security) for OpenSSL streams, a preload feature, PHP FPM system (Fast Process Manager) for better optimization of codes, and so on.

What's New in TLS 1.3?

Transportation Layer Security (TLS) 1.3 protocol provides better privacy and performance standards compared to previous versions of TLS.

TLS 1.3 reduces latency, optimizes code performance and security of your encrypted connections using OpenSSL streams. The rapid adoption of Cloudflare TLS 1.3 in all modern browsers for e.g., Microsoft Edge started supporting TLS 1.3 with version 76 and draft version of TLS 1.3 was enabled in Firefox 52 that allow building a safer and faster web and also influencing the web development standards.

What's New in PHP FPM?

The primary benefit of using PHP-FPM in your coding task is having more efficient «PHP handling» and the ability to use «opcode caching» for PHP scripts.

PHP-FPM’s is built on an event-driven framework that allows PHP scripts to use as much of the server’s resources without using the additional overhead that comes from running them inside of web server processes.

PHP-FPM can reuse worker processes repeatedly instead of having to create and terminate them for every single PHP request. PHP-FPM can serve more traffic than traditional PHP handlers while creating greater resource efficiency.

Let's Continue with FFI Best Practices

If you use PHP FFI moving forward you should have less of a need to write new PHP modules for interfacing with C libraries/programs. This can now can be done using the foreign function interface.

If you need to run resource-intensive code, you can use a foreign function interface for the task — extensive parsing, number crunching, complex rendering, etc. You can «glue» two code bases together inside a single program without using two entirely different programs. Programmers can have a good C-ABI library readily available with FFI extension. It will save your time, as you don't need to rewrite code in PHP.

FFI also provides performance boosts to your coding task. Python has become one of the most popular languages for machine learning because of FFI because it makes Python codes relatively simple to load and allows using powerful C-ABI libraries in Python using FFI extension.

8. Preloading in PHP 7.4 (One of My Favorites)


Let’s talk about Preloading. When using libraries or frameworks in PHP, the code files need to be linked properly and they need to load on every request.

With a feature like Preloading, programmers can load frameworks and libraries into the OPCache, which allows the server to load the PHP files and store them in memory. This is all about making your code perform efficiently and quickly!

Preloading is run by a specific php.ini directive or opache.preload. It has the script compiler that executes when the server starts working. It can also be used to preload more files or compile them.

php.ini function

This feature is awesome to use, as the preloaded files always remain cached in OPCache memory forever.

Why You Should Upgrade To PHP 7.4?


According to WordPress.org statistics, 36.4% of WordPress sites are still on PHP 5.6. Let that sink in.

This means websites that continue to use PHP 5.6 could be exposed to vulnerabilities. And in many cases, it’s up to developers to get these sites upgraded.

I know this can be a time-consuming task for a developer using older plugins and themes. Updating to the latest version of PHP involves updating your code along with extensive testing to ensure compatibility. After all, you don’t want to break your users' sites.

This means that if you want your site running on the latest version of PHP, you’ll need to take the initiative and upgrade it yourself or get someone from your site developer or hosting provider to do it.
Upgrading to PHP 7.4 comes with benefits of speed, performance, and security. As mentioned above, it has a lot of new features. Let's look at some of them more in-depth now.

The FFI (Foreign Function Interface)

This is a completely new extension that opens up new ways of development. For example, it can be used with machine learning and similar technologies. Just keep in mind – it is still in the experimental phase.

Preloading

Preloading is also quite useful as it allows the loading of PHP classes or functions directly into the memory.

For example, when I try to run a program in PHP, it makes me work faster. It is better than the usual auto-loading approaches.

This is an extremely important feature for web developers as it has the long-term potential to be used instead of auto-loading in certain cases.

Overall, it's a different experience now of compiling PHP codes with the FFI extension. It also opens up a whole new world of possibilities for PHP developers beyond the web.

Speed and Performance


If your site is running on an older version of PHP, updating to the latest version of PHP will give you immediate performance gains.

All functions and most classes will be permanently loaded into PHP's function and become permanently available in the context of any future request and improve code performance.

  • PHP 7.4 helps resolve class dependencies and links with the parent, interfaces, and traits. This is something that doesn't happen with the older version of PHP or Opcode caching).
  • PHP removes unnecessary codes and performs other optimizations.
  • By having the code for an entire application, including its framework (such as Symfony, and Laravel) preloaded into memory, most applications will perform significantly better.

Support and Compatibility


Working on old software is costly and can be risky in terms of adding new features and performance enhancement features to your products—and supporting older versions of PHP holds them back.

PHP has always been known for its ease of coding, which is one reason why it’s a popular language for many new web developers. To help with this, many aspects of PHP 7.4 attempt to steer new developers in the right direction. It does this by removing poorly written, outdated functions previously kept in for backward compatibility reasons.

With the adoption of PHP 7.4, you should begin to see a higher standard of PHP coding. In turn, this should also help PHP become more respected as a development language, attracting talent that has otherwise avoided it.

Security


Another fundamental reason why you should upgrade to PHP 7.1 or newer is the security of your WordPress site. Running the latest version of PHP ensures that your site is protected against vulnerabilities like, for example, Code execution, SQL injection, Cross-Site Scripting or XSS, and many other types of vulnerabilities out there.

Code injection vulnerabilities occur where the content served from a web application can be manipulated in such a way that it triggers server-side code execution. In some poorly written Web applications that allow users to modify server-side files, it is sometimes possible to inject code in the scripting language of the application itself.

Cross-site Scripting (XSS) is a client-side code injection attack. The attacker aims to execute malicious scripts in a web browser of the victim by including malicious code in a legitimate web page or web application.

SQL injection (SQLi) is a type of injection attack that makes it possible to execute malicious SQL statements. These statements control a database server behind a web application. Attackers can use SQL Injection vulnerabilities to bypass application security measures.

Sounds amazing, right? All you need to do is upgrade to the latest version of PHP. But first...

Checking For PHP Compatibility


Updating to the latest version of PHP has many benefits, as we just discussed. However, before you go and update it, make sure you check what version of PHP your website is using. You should also check your site’s compatibility with the latest version of PHP.

If you are not sure which version of PHP you're using, here's how you can check: just install this free Display PHP Version plugin. It can be downloaded from the WordPress plugin repository.

Once you've installed it, simply activate it and it will display your website's version of PHP (you can find it in the “At a Glance” option in the WordPress dashboard).

Final Words


Best practices for PHP have always been about improving the developer experience. In general, you have to fully understand all the benefits and drawbacks of any project before committing to work on it. Modern PHP development concepts give you a true and easy way of writing software.

So, turbocharge your website with PHP's latest version. If you need help upgrading to PHP 7.4, or with auto-scaling, performance issues, website development, or security, let me know and I'd be happy to provide feedback.
Tags: php web development mobile app development ecommerce solutions ecommerce solution ecommerce website ecommerce platforms
Hubs: Website development PHP Development of mobile applications Development for e-commerce Software
-4
1.3k 2
Comments 3
Ads
Top of the day