Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
The Art of Modern PHP 8
The Art of Modern PHP 8

The Art of Modern PHP 8: Learn how to write modern, performant, and enterprise-ready code with the latest PHP features and practices

eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

The Art of Modern PHP 8

Chapter 1: Object-Oriented PHP

In this first part of the book, we are going to explore modern object-oriented PHP. While there isn't sufficient space in this book to do a deep dive into this topic, we hope that you will be able to use the contents of the following three chapters as a jumping point for your own further study and experimentation. To be clear, for any PHP language features you see that you don't understand, you are absolutely encouraged to put the book down and go and start reading the PHP docs so that you can gain a fuller understanding of that particular feature. To underline this, you will see frequent links to the official documentation. You are encouraged to follow these links and read into any feature that you are not intimately familiar with.

Some readers may already be very familiar with object-oriented programming (OOP) in PHP and for those, this first part might be a nice refresher. You never know, you might learn something new! If you are not familiar with modern object-oriented PHP, then there is likely to be a lot to take in. I seriously hope you don't find this overwhelming. All I can say is, it's worth persevering as OOP is fundamental to modern PHP.

This chapter is an introduction to OOP in general and includes a review of some popular object-oriented PHP projects and frameworks that you are encouraged to go and have a look at.

By the end of part 1, especially if you take the time to fill in the gaps by hitting the official docs, you should be fairly up to date with how OOP works in modern PHP.

The following topics will be covered in this chapter:

  • What is OOP?
  • PHP OOP basics

Before we begin this chapter in depth, you are strongly encouraged to have a thorough read through the official documentation on classes and objects:

PHP: Classes and Objects - Manual

https://www.php.net/manual/en/language.oop5.php

In this chapter, we are going to look in general at what we mean by OOP and what it means to you. We'll start by understanding what the phrase OOP actually means and compare it to some other programming styles. I will recommend some PHP projects and packages that you can look at if you want to get your hands dirty with an existing code base. After that, we are going to jump in at the deep end with a look at inheritance, and then also look at using composition instead of inheritance. After that, we'll take a quick look at the Standard PHP Library, have a look at exceptions, and understand how modern PHP projects ensure that they have robust error handling. For the big finale of this chapter, we'll dip our toes in the deep waters of metaprogramming with reflection and attributes. It's a huge amount of content to cover in a comparatively tiny amount of text.

For this chapter, and all the other chapters in the book, you can find all the code samples in the main repo for the book available on GitHub at https://github.com/PacktPublishing/The-Art-of-Modern-PHP-8

What is OOP?

If you don't really know what OOP even means, then this section is for you! We're going to take a step back and start right from the beginning to try to understand the meaning of the phrase, then try to understand OOP as compared to other programming styles, and finally, have a quick tour of some modern object-oriented PHP packages and projects.

So, let's get started with looking at what OOP really means.

Understanding the phrase

OOP stands for object-oriented programming. It sounds like one of those CS phrases that get bandied about quite a bit without people really understanding what they mean. Let's unpack it, starting from the end

Programming

Hopefully, you already have a good idea of what we mean by programming. PHP is a programming language and by that we mean simply that it is a set of coding words, symbols, and phrases that you can use to create code that ultimately does something.

There is a lot of inane debate about whether PHP truly is a programming language but let's not go there. We're here to get things done and that is where PHP excels.

Oriented

Oriented means "showing the direction in which something is aimed, directed towards or interested in something." So, we're programming in a way that is directed toward or interested in something. The "something" we are interested in is objects. In OOP, we use classes and objects for everything.

Object

What is an object? Well, in PHP, an object is an "instance" of a "class."

Here is the simplest class in PHP

<?php
class Foo {}

Simply enough, it is defined with the word class and it has a name and then a body, which is delineated by the curly braces. On its own, this is pretty useless, of course. It gets more interesting as we add code to the body of the class and meta information to the class definition.

To create an object, we use the word new and can then optionally assign the result of this call to a variable. We now have an object:

<?php
$foo = new Foo();

When we are talking about OOP, what we really mean is that we will compose our program entirely using objects. There must always be some code that resides at the global scope, but in an OOP program, this code is very limited indeed and is simply used to bootstrap and initialize the OOP code.

For example, this is the index.php file that all web requests are directed to when looking for a page in a Symfony project:

public/index.php

Repo: https://git.io/JqJxu

<?php
use App\Kernel;
use Symfony\Component\Dotenv\Dotenv;
use Symfony\Component\ErrorHandler\Debug;
use Symfony\Component\HttpFoundation\Request;
require dirname(__DIR__).'/vendor/autoload.php';
(new Dotenv())->bootEnv(dirname(__DIR__).'/.env');
if ($_SERVER['APP_DEBUG']) {
    umask(0000);
    Debug::enable();
}
if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? false) {
    Request::setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST);
}
if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? false) {
    Request::setTrustedHosts([$trustedHosts]);
}
$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

As you can see, every single line of code apart from the call to umask is instantiating or calling methods on classes or objects. The file procedurally represents an entire application, and the entire application's code is encapsulated in the classes instantiated in this file, and the classes they are composed of.

OOP alternatives

It might be easier to understand what OOP is if we compare it with other programming styles. Let's explore two other programming styles to help deepen our understanding.

Procedural programming

This is the classic PHP style and is probably the reason why PHP often gets bad press. Procedural code works like a long list of instructions. You start at the top and continue reading till you hit the bottom.

Of course, all code works like this really, but the point is that in procedural code, there is much less use of scoping. A lot of work is done in the global scope, though there will generally be lots of calls to global functions and maybe even a few objects floating around.

The benefit of procedural code is that it is highly optimized for writing. You can write the code like a logical stream of consciousness.

The downsides to procedural code are that it can be quite difficult to reuse chunks of code, there can be a large number of variables in the global scope, which can make debugging things somewhat challenging, and finally, the ability to test distinct parts of the code is somewhat diminished – you can only really test the system as a whole with end-to-end tests.

One procedural project that has stood the test of time and is almost unbelievably popular and successful is WordPress:

GitHub – WordPress/wordpress-develop

https://github.com/WordPress/wordpress-develop

I think it would be fair to say that the exception proves the rule, though – the general trajectory of modern PHP has gone very much toward OOP.

Procedural code can be great for creating smaller scripts of maybe 1-200 lines, but for building full-blown projects it is no longer regarded as a good idea by most PHP developers.

The chunk of code you are about to read is entirely fictional but created from long years of dealing with this kind of code in production. It's big, verbose, and old-fashioned. I'm sure many of you will recognize this kind of file. Those of you that don't, count your blessings!

<?php
# product_admin.php
// bring in an application top file that contains 1000 lines of bootstrapping and including things
require __DIR__.'/../../application_top.php';
if(isset($_GET['products_id'])){
    // 500 lines of product related stuff
    if(isset($_POST['action'])){
        switch($_POST['action']){
            // 1000 lines of various post actions that might be happening
        }   
    }
}

In procedural code, it is normal for each page type to have its own file – this means that public traffic can be loading lots of different PHP files. Your public htdocs folder will generally include a number of PHP files that are publicly accessible and executable, possibly in subfolders as well for different system areas.

Functional programming

Functional programming, as its name implies, predominantly uses functions as the building blocks of code. In functional programming, we try to use "pure functions."

Pure functions are those functions that, when given specific values as inputs, will do the following things:

  1. Always return the same value
  2. Never cause any side effects

Pure functions are fantastic because they are very easy to reason about, very easy to test, and are completely 100% decoupled from any other code or state.

PHP has a powerful functional model and can be a great language for functional styles. I will admit I have never seen a code base in PHP that you would regard as purely written in the functional programming style, but you do often see functional programming styles utilized in OOP and procedural code.

A deep dive into functional programming in PHP is beyond the scope of this book; however, I really encourage you to learn more about functional programming in PHP and hit these docs pages:

Here is a contrived example of how a functional programming index.php file might look:

<?php
declare(strict_types=1);
require __DIR__.'/../functions.php';
(function(string $responseTxt, array $headers):void{
    array_map(
        fn(string $header):void => header($header), 
        $headers
    );
    echo $responseTxt;
})(...(function(array $request):array{        
    $headers=[];
    $responseTxt='';
    // some code to actually generate the page and headers
    return ['headers'=>$headers, 'responseTxt'=>$responseTxt];
})($_REQUEST));

While I have never actually seen a proper functional programming-based project in the real world, you can and do see functional programming styles applied to OOP and procedural projects. The benefits of using pure functions and avoiding a shared state are applicable to all forms of programming.

So, now that we have looked at some alternative programming styles, let's move on to ways you can start to learn object-oriented PHP.

Learning object-oriented PHP

The first resource you should hit when learning PHP is the official documentation:

PHP: Classes and Objects - Manual

https://www.php.net/manual/en/language.oop5.php

This is good, though I do suggest you avoid the comments as many are very old and not relevant at all.

Probably the easiest way to get your head around OOP in PHP is to work on an existing open source project or framework that is written in the OOP style. There are many to choose from, though the quality can vary.

Here is a quick introduction to some popular projects.

Frameworks

The two most popular PHP frameworks are Laravel and Symfony. All modern PHP frameworks that I am aware of adopt the Model, View, Controller (MVC) structure.

In a nutshell, this means that all requests are directed to a single "front controller," which then handles deciding exactly what the request is asking for and then routing that to the correct Controller. What that means is that there is a single publicly accessible index.php file as the only public PHP file in the htdocs folder.

The Controller's job is to utilize the Model to retrieve any data required and perform any required processing before finally utilizing the View to return a string of text to be rendered as HTML. It's worth reading more on MVC if this is not something you are familiar with.

Symfony

Symfony is one of the oldest PHP frameworks (in active development since 2005) and has matured with the language over time.

It is a great choice for "enterprise" projects that require stability and a clear support lifetime. The general wisdom is that Symfony might be a better choice for long-term projects that are likely to grow in complexity over time.

The way that modern Symfony is constructed is highly modular; it allows you to keep the scale of your application as lean as possible, only bringing in functionality that you need.

Symfony is built upon the concept of "Components," which are actually framework-agnostic decoupled libraries that perform a certain function. This means that the code base as a whole is kept very clean, and you can work in a way that is less about the framework.

To find out more about Symfony, visit:

GitHub - symfony/symfony: The Symfony PHP framework

https://github.com/symfony/symfony

Laravel

Laravel is by far the most popular PHP framework at the moment. Laravel uses a lot of Symfony components under the hood, which underlines how good the Symfony stuff is. Where Laravel and Symfony differ is primarily in their approach and philosophy.

The general wisdom is that Laravel is easier and faster to work with for more simple projects, but if you are expecting to build the kind of project that might grow very complex over time, then Symfony might be a better choice.

To learn more about Laravel, go to:

GitHub - laravel/laravel: A PHP framework for web artisans

https://github.com/laravel/laravel

Slim

If you are looking to build something simple, such as a plain API, then you might enjoy working with more of a micro framework such as Slim.

More information on Slim can be found at:

GitHub - slimphp/Slim: Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.

https://github.com/slimphp/Slim

Roll your own!

This is not something that I would recommend for a real production site, but for a personal project, you can't really beat the experience of creating your own bespoke MVC framework.

If you want to avoid reinventing the wheel, you could take the same tack as many successful projects and utilize Symfony components for your basic building blocks, such as HttpKernel.

Find out more here:

GitHub - symfony/http-kernel: The HttpKernel component provides a structured process for converting a Request into a Response.

https://github.com/symfony/http-kernel

Applications

Learning frameworks is all well and good, but if you need to solve a fairly standard project such as building an online shop or some form of blog or brochure site, then you might be better off choosing a more complete package that already includes all the basic features you need.

I have pulled together a few suggestions for you. These are all generally framework-based and so can give you some good ideas on how to use a framework in a full application.

E-commerce

An area where PHP really shines in terms of theopen source packages available is e-commerce. The main problem facing the modern e-commerce PHP developer is that there is so much choice!

Sylius

Sylius is Symfony-based and has been built using modern practices such as test-driven development (TDD) and behavior-driven development (BDD). It doesn't really claim to be the "all bells and whistles included" platform that perhaps Magento does, but instead it offers itself as a solid platform for a more bespoke e-commerce solution.

Find Sylius here:

GitHub - Sylius/Sylius: Open Source eCommerce Platform on Symfony

https://github.com/Sylius/Sylius

Magento

Magento is the big daddy in open source PHP e-commerce. Magento is based on quite an old-fashioned framework at its core and is unusual in that it does not use Symfony or Laravel as its framework. Magento 2 uses some interesting strategies such as "aspect-oriented programming" and extensive use of code generation.

Want to know more? Visit:

GitHub - Magento

http://github.com/magento/magento2

Shopware

The latest version of Shopware is Symfony-based and aims to provide Magento levels of functionality with the development best practice approach of Sylius. It's an interesting proposition and definitely worth a look.

Check Shopware out here:

GitHub - shopware/platform: Shopware 6 is an open source e-commerce platform realised by the ideas and the spirit of its community.

https://github.com/shopware/platform

CMS

Content management systems (CMSes) are designed to manage generic content-driven sites such as blogs and brochure sites. WordPress alone powers a huge percentage (at least 30%, maybe close to 40%) of sites on the internet, with big names such as techcrunch.com and blog.mozilla.org proudly running the platform.

Drupal

Drupal has been a very popular CMS in the PHP world for a long time and has gradually morphed from procedural roots into a modern OOP system.

Drupal uses Symfony components such as HttpKernel and routing components along with other more modular components such as Twig and YAML. Drupal 7 had its own components (kernel, router, templating, config management, and so on), and then Drupal 8 was an almost rewrite with more Symfony components and an OOP approach.

It is a large-scale CMS platform suitable for bigger-content projects. It is not a pure Symfony framework project but is a good example of a project that has managed to make itself more object-oriented over time and thereby improved the developer experience significantly.

More on Drupal here:

project / drupal · GitLab

https://git.drupalcode.org

OctoberCMS

October CMS is a much smaller project than Drupal but worth a look if you prefer something Laravel-based.

Check it out here:

GitHub - octobercms/october: Free, open source, self-hosted CMS platform based on the Laravel PHP Framework.

https://github.com/octobercms/october

Joomla

Another CMS project with a long history is Joomla. At the time of writing, version 4 is being actively developed. This brings things significantly up to date in comparison to the current version 3.

The main project is here:

GitHub - joomla/joomla-cms at 4.1-dev

https://git.io/JZZ5h

You can look at some of the various components they have developed here:

Joomla! Framework · GitHub

https://git.io/JZZ5j

So, this is the end of our What is OOP? section. I hope that you now understand what the phrase means and have perhaps even had a chance to peruse some of the code bases suggested so you have an understanding of what object-oriented PHP looks like. Maybe you've even been inspired to kick the tyres on a new project or even have a go at rolling your own. I've heard it said that every PHP developer has an MVC framework in them.

Now it's time to move on to looking at some technical details of object-oriented PHP.

PHP OOP basics

In this section, we are going to cover a very brief overview of the basic OOP features of PHP 8. I am not aiming to be comprehensive here; if this is new to you, then I suggest you visit the official docs, which do a great job of explaining these features in detail:

PHP: Classes and Objects - Manual

https://www.php.net/manual/en/language.oop5.php

We will be covering further details throughout the book; however, the following should be enough to whet your appetite and let you know whether your knowledge is up to date. We're going to look briefly at classes, interfaces, and namespaces. This should all be quite familiar to you already and if it is not, then a little extra revision of these topics would be useful so that you can get the most out of later chapters.

Classes

The basic building block of PHP OOP is the class. As briefly mentioned earlier in this chapter, classes are the things that get instantiated in the "objects" that OOP talks about.

A simple class looks like this:

src/Part1/Chapter1/Simple/SimpleClass.php

Repo: https://git.io/JRw7C

<?php
declare(strict_types=1);
namespace Book\Part1\Chapter1\Simple;
class SimpleClass
{
    public function __construct(public string $name = 'Simon')
    {
    }
}

To create an instance of the class, we use the new keyword, which then gives us an "instance" that we can assign to a variable and generally interact with.

Then, a new instance is created; PHP will check for a method called __construct and if it exists, it will be called. The parameters passed into this method are those that are passed in when calling the class:

src/Part1/Chapter1/simple.php

Repo: https://git.io/JRw7W

<?php
declare(strict_types=1);
namespace Book\Part1\Chapter1;
use Book\Part1\Chapter1\Simple\SimpleClass;
require __DIR__ . '/../../../vendor/autoload.php';
$instance = new SimpleClass();
echo "\n" . $instance->name; // Simon
$instance2 = new SimpleClass('Sally');
echo "\n" . $instance2->name; //Sally

Output:

Inside the class, we have a variable called $this, which is available to every method inside the class and refers to the current instance. It provides access to all the methods and properties of that instance:

src/Part1/Chapter1/Simple/SimpleWithGetter.php

Repo: https://git.io/JRw7l

<?php
declare(strict_types=1);
namespace Book\Part1\Chapter1\Simple;
class SimpleWithGetter
{
    public function __construct(private string $name = 'Simon')
    {
    }
    public function getName(): string
    {
        return $this->name;
    }
}

If the parameters are defined in the constructor with a visibility keyword (private, protected, or public), then the parameter will automatically be defined as a property of the class with that visibility level.

If a visibility level is not specified, then in order to assign the parameter value to the class as a property, we have to do something like this:

src/Part1/Chapter1/Simple/SimpleManualAssignment.php

Repo: https://git.io/JRw78

<?php
declare(strict_types=1);
namespace Book\Part1\Chapter1\Simple;
class SimpleManualAssignment
{
    private string $name;
    public function __construct(string $name = 'Simon')
    {
        // take the constructor param and manually assign to class property
        $this->name = $name;
    }
}

There are three ways that properties can be set in the class:

  • In the constructor parameters
  • Defining the property in the class body
  • Dynamically assigning the property without a definition (don't do this)

Have a look at the following snippet, which demonstrates these three options:

src/Part1/Chapter1/Simple/SimplePropertyAssignment.php

Repo: https://git.io/JRw74

<?php
declare(strict_types=1);
namespace Book\Part1\Chapter1\Simple;
class SimplePropertyAssignment
{
    private string $defined = 'defaultValue';
    public function __construct(
        private string $constructorParam = 'constructorValue'
    ) {
        // this is a bad idea, dynamicProperty is untyped and public
        $this->dynamicProperty = 'dynamicallyAdded';
    }
}

When a property is declared dynamically, it can only ever be public, and it cannot be typed. This means that we lose a huge amount of safety and open the door to a whole range of bugs:

src/Part1/Chapter1/simple_properties.php

Repo: https://git.io/JRw7B

<?php
declare(strict_types=1);
namespace Book\Part1\Chapter1;
use Book\Part1\Chapter1\Simple\SimplePropertyAssignment;
require __DIR__ . '/../../../vendor/autoload.php';
$instance = new SimplePropertyAssignment();
// dynamic property is public
echo "\n" . $instance->dynamicProperty;
// dynamic property is untyped and can be anything
$instance->dynamicProperty = 123;
echo "\n" . $instance->dynamicProperty;

Output:

As you hopefully now realise, public properties are generally not something you want, apart from in very particular circumstances. If you ever see dynamically assigned properties, the general expectation is that it is a mistake, and for this reason, most integrated development environments (IDEs) will highlight it as a warning.

Interfaces

Interfaces are pieces of code that never contain any functionality, but what they do define are the… well… interface that classes must provide when they implement the specific interface.

For example:

src/Part1/Chapter1/interface.php

Repo: https://git.io/JRw7R

<?php
declare(strict_types=1);
namespace Book\Part1\Chapter1;
interface GetsSomethingInterface
{
    /**
     * This interface defines one method.
     * It must be called "getSomething" and it must return a string
     */
    public function getSomething(): string;
}
class GetsSomethingClass implements GetsSomethingInterface
{
    public function getSomething(): string
    {
        return 'something';
    }
}
echo "\n" . (new GetsSomethingClass())->getSomething();

Output:

By implementing an interface, the class tells the world that it conforms to a set of strict rules. It must implement the methods in the interface as they are defined. That allows other code to not necessarily care exactly what class it is and confidently call methods as we know they will be there, and we know what types they will return.

Read more about interfaces in the official docs:

PHP: Object Interfaces - Manual

https://www.php.net/manual/en/language.oop5.interfaces.php

Namespaces

This is not strictly part of OOP but is highly relevant, so I'm including it here. Namespaces are designed to make naming things a lot, lot simpler. Before we had namespaces, our code needed to worry about the fact that there might be a situation where some other piece of code tries to use the same name as the one you are trying to use for your class, function, or another item. This led to things having very long names, such as Mage_Catalog_Product_CompareController – all in an effort to ensure that there is no risk of a name clash, because a name clash is a fatal error.

The advent of namespaces meant that we could now define a clean slate for naming things. We need to define a unique namespace and then within that namespace, we can give things lovely, short, meaningful names with no fear of a name clash:

<?php
namespace My\Library;
class Helper {}
function write(string $value){}

There is nothing in PHP itself that defines which namespace any particular file should use; however, modern PHP developers have almost completely adopted something called PSR-4:

PSR-4: Autoloader - PHP-FIG

https://www.php-fig.org/psr/psr-4/

As you can see if you follow the link, PSR-4 lays out rules around exactly how to use namespaces and how they should correspond to the file/folder structure of your project.

What is PSR?

If you haven't heard of PSR before, it might be worth reading into it a bit. PSR stands for PHP Standards Recommendations. It is something that was put together and promoted by a group of PHP developers called the PHP Framework Interop GroupPHP-FIG for short.

What they have done is tried to put together coding standards and basic interfaces to define general components. The goal is that rather than each framework being its own weird and wonderful isolated pond, there are standard approaches to standard problems. The huge advantage of this is that tooling and libraries are less coupled to frameworks and we can have nice things that were primarily built for one framework or application being useable by the rest of the PHP ecosystem. DI containers are actually a great example of this.

This policy defines a folder structure and naming convention that corresponds a class's namespace. Each \ in the namespace name corresponds to a subdirectory in the folder structure, with a defined prefix applied within a defined base directory.

This example is copied from the PSR-4 page:

If you have been paying close attention to the code snippets, you may have spotted that the example code for this book also conforms to PSR-4. The root namespace prefix is Book\ and this corresponds to the src directory in the code repo. For code that is designed to be shared publicly, this root namespace is like a unique username or brand and is generally standardized for all packages released by the same person or company. We will explore these kinds of packages later in the book.

For any files in the base directory, the namespace is simply the namespace prefix. If the file is in a subfolder, then the namespace is extended to match the subfolder name.

If you look back through the code snippets in this chapter, you can see that as we are in Part1 and Chapter1, the code snippets are being stored in src/Part1/Chapter1, and for each code snippet that is in that folder, the namespace is defined as follows:

namespace Book\Part1\Chapter1;

Any code snippets in a subfolder have the namespace extended to match; for example, the file /src/Part1/Chapter1/Simple/SimplePropertyAssignment.php has the namespace defined as follows:

namespace Book\Part1\Chapter1\Simple;

PSR-4 is a very sane and sensible system to follow, and I highly encourage you to do so.

Read more about namespaces in the official docs:

PHP: Namespaces - Manual

https://www.php.net/manual/en/language.namespaces.php

Summary

This brings us to the end of our first chapter. Let's quickly recap what we have covered. First of all, we explored what the term OOP actually means. We looked at some other programming styles and used this to compare with some OOP code to hopefully highlight the differences. We then had a quick look through some popular PHP OOP projects that are worth looking at in more detail if you would like to see some real-world code and maybe get your hands dirty. Finally, we had a very quick overview of some basic OOP features. You should already know these in detail and so we didn't go over them in any depth – if you do not already know them, then you are encouraged to hit the official docs to fill in the gaps. In the next chapter, we are going to look at some more advanced topics in object-oriented PHP related to the ways that we can orchestrate a graph of related objects, either using inheritance or, alternatively, using composition.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Explore the latest PHP 8.1 features and modern web development practices
  • Refactor your legacy codebase using modern features and styles in PHP
  • Create your own Composer packages that can be reused across all PHP projects

Description

PHP has come a long way since its introduction. While the language has evolved with PHP 8, there are still a lot of websites running on a version of PHP that is no longer supported. If you are a PHP developer working with legacy PHP systems and want to discover the tenants of modern PHP, this is the book for you. The Art of Modern PHP 8 walks you through the latest PHP features and language concepts. The book helps you upgrade your knowledge of PHP programming and practices. Starting with object-oriented programming (OOP) in PHP and related language features, you'll work through modern programming techniques such as inheritance, understand how it contrasts with composition, and finally look at more advanced language features. You'll learn about the MVC pattern by developing your own MVC system and advance to understanding what a DI container does by building a toy DI container. The book gives you an overview of Composer and how to use it to create reusable PHP packages. You’ll also find techniques for deploying these packages to package libraries for other developers to explore. By the end of this PHP book, you'll have equipped yourself with modern server-side programming techniques using the latest versions of PHP.

Who is this book for?

The book is for existing PHP developers and CTO-level professionals who are working with PHP technologies, including legacy PHP, in production. The book assumes beginner-level knowledge of PHP programming as well as experience with server-side development.

What you will learn

  • Understand how to use modern PHP features such as objects, types, and more
  • Get to grips with PHP package management using Composer
  • Explore dependency injection for your PHP applications
  • Find out what the differences are between legacy and modern PHP 8 code and practices
  • Write clean PHP code and implement design patterns
  • Get hands-on with modern PHP using examples applying MVC and DI techniques

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 26, 2021
Length: 420 pages
Edition : 1st
Language : English
ISBN-13 : 9781800566156
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Oct 26, 2021
Length: 420 pages
Edition : 1st
Language : English
ISBN-13 : 9781800566156
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 102.97
The Art of Modern PHP 8
€32.99
PHP 8 Programming Tips, Tricks and Best Practices
€41.99
Clean Code in PHP
€27.99
Total 102.97 Stars icon

Table of Contents

18 Chapters
Section 1 – PHP 8 OOP Chevron down icon Chevron up icon
Chapter 1: Object-Oriented PHP Chevron down icon Chevron up icon
Chapter 2: Inheritance and Composition, Encapsulation and Visibility, Interfaces and Concretions Chevron down icon Chevron up icon
Chapter 3: Advanced OOP Features Chevron down icon Chevron up icon
Section 2 – PHP Types Chevron down icon Chevron up icon
Chapter 4: Scalar, Arrays, and Special Types Chevron down icon Chevron up icon
Chapter 5: Object Types, Interfaces, and Unions Chevron down icon Chevron up icon
Chapter 6: Parameter, Property, and Return Types Chevron down icon Chevron up icon
Section 3 – Clean PHP 8 Patterns and Style Chevron down icon Chevron up icon
Chapter 7: Design Patterns and Clean Code Chevron down icon Chevron up icon
Chapter 8: Model, View, Controller (MVC) Example Chevron down icon Chevron up icon
Chapter 9: Dependency Injection Example Chevron down icon Chevron up icon
Section 4 – PHP 8 Composer Package Management (and PHP 8.1) Chevron down icon Chevron up icon
Chapter 10: Composer For Dependencies Chevron down icon Chevron up icon
Chapter 11: Creating Your Own Composer Package Chevron down icon Chevron up icon
Section 5 – Bonus Section - PHP 8.1 Chevron down icon Chevron up icon
Chapter 12: The Awesomeness That Is 8.1 Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(9 Ratings)
5 star 66.7%
4 star 22.2%
3 star 0%
2 star 0%
1 star 11.1%
Filter icon Filter
Top Reviews

Filter reviews by




Lalithkumar Oct 17, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Best book i have read for php
Subscriber review Packt
Shailesh Bopche Feb 16, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is a must-read for PHP developers wishing to better their skills, in my opinion. Not only will they gain an informed and practical perspective on PHP8, but they'll also take away the sorts of things I emphasise in code reviews on a regular basis; it's a true window into how clean PHP code is written and what your codebase can be. The book and its accompanying github repository will walk readers through the process of creating their own bespoke, bonified modern MVC framework, complete with modern test-driven development (if they look in the /tests folder), and how to make those decisions. It also demonstrates how to use these strategies to increase code readability in existing codebases. - Jay Joseph
Amazon Verified review Amazon
Amazon Customer Feb 24, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is fantastic for the new and the advanced. The writer(s) did a fantastic job of providing a baseline and understanding of php, and then referencing resources that will allow you to go down the php rabbit hole. If you want to go from beginner to expert, then I suggest checking out this book.
Amazon Verified review Amazon
AJ Jan 11, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book has helped me overcome some barriers. The author does a really good job explaining concepts. I worked with PHP long ago and just stopped to work on other languages. This book made me pick it right back up. There are new concepts that is mentioned in this book. This made me learn MVC. I have been working with MVVM for a bit. I need to start working on server side now!One of the most important things to do in any field is stay up to date with whats going on within that field. This author does a really good job at that. I will be looking for more.
Amazon Verified review Amazon
Brad S Dec 24, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Excellent coverage of PHP OOP and new additions in PHP 8. Also has a couple of chapters on writing your own composer package which I've found very helpful. Overall a great book to help you level up your PHP skills!
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.