Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
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
$24.99 $35.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
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 : 9781800563223
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 135.97
The Art of Modern PHP 8
$43.99
PHP 8 Programming Tips, Tricks and Best Practices
$54.99
Clean Code in PHP
$36.99
Total $ 135.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

Most Recent
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
Most Recent

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
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
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
William Bostic Jan 16, 2022
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Although the book states up front that it is useful for beginners as well as advanced php programmers, my opinion is it’s far better suited for intermediate and advanced users. The author is an expert php developer with extensive and comprehensive insight. At times it almost reads like a formal paper written at the computer scientist level. The benefit of this style is that it’s extremely concise and packed with information. The con is that it’s like drinking from a fire hose! It’s definitely not light reading LOL. The book might have been better called: Deep Dive into PHP Development. There’s many great insights about the php ecosystem, and the book is laden with extensive references (like a formal paper or thesis). While I am impressed with the comprehensive perspective presented, I found it somewhat overwhelming and difficult to read. If you are a PHP wiz you will probably love it.
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
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.