Reader small image

You're reading from  Building RESTful Web Services with PHP 7

Product typeBook
Published inSep 2017
Reading LevelIntermediate
PublisherPackt
ISBN-139781787127746
Edition1st Edition
Languages
Tools
Concepts
Right arrow
Author (1)
Waheed ud din
Waheed ud din
author image
Waheed ud din

Haafiz Waheed-ud-din Ahmad has been working in the IT industry since 2008. He has mostly worked in web application development and mostly used PHP at the server side. Although most of his experience is in PHP, he is a technology agnostic person and also likes to learn and adapt to new technologies. He also acts as an adviser for startups and new developers. He has worked on Python and JavaScript as well. He likes to experiment with new technologies, and he has also explored Golang, Scala, and Neo4J. He also has a keen interest in data science and big data domain and has worked on D3.js for data visualization. He is not just a technology enthusiast but also likes to solve day-to-day problems by the usage of technology. You can follow him on twitter at @Haafiz786.
Read more about Waheed ud din

Right arrow

Chapter 2. PHP7, To Code It Better

PHP7 came with many new features and changes. However, none of them were specifically for REST or web services. In fact, REST does not have any direct relation with language constructs. This is because REST is an architecture, while a language is there to provide constructs for implementation. So, does that mean PHP7 has some construct or feature which can make this implementation better? Yes and no. It depends on what we mean by implementation.

If we mean just getting a request and returning a response then No, there is no such specific feature. But, any RESTful Web Service is related to an entity, and an entity can have its own logic. So to provide RESTful Web Service for that entity, we need to write that logic as well. For this purpose, we will need to write more PHP code than just getting a request and returning a response. So to keep the code simple and clean, yes, PHP7 offers us many things.

I assume that you have the basic knowledge of PHP, as knowing...

Scalar type declaration


In PHP7, we can now declare the type of parameters passed to a function. They could be only user defined classes in previous versions, but now they can be scalar types as well. By scalar type, we mean basic primitive types, such as int, string, and float.

Previously, to validate an argument passed to a function, we needed to use some sort of if-else. So, we used to do something like this:

<?php
function add($num1, $num2){
    if (!is_int($num1)){
        throw new Exception("$num1 is not an integer");
    }
    if (!is_int($num2)){
        throw new Exception("$num2 is not an integer");
    }

    return ($num1+$num2);
}

echo add(2,4);  // 6
echo add(1.5,4); //Fatal error:  Uncaught Exception: 1.5 is not an integer

Here we used if to make sure that the type of the variables $num1 and $num2 is int, otherwise we are throwing an exception. If you are a PHP developer from the earlier days who likes to write as little code as possible, then chances are that you were...

Return type declaration


Just like parameter type, there is also a return type; it is also optional it is a safe practice to specify the return type.

This is how we can declare a return type:

<?php
function add($num1, $num2):int{
    return ($num1+$num2);
}

echo add(2,4); //6
echo add(2.5,4); //6

As you can see in the case of 2.5 and 4, it should be 6.5, but as we have specified int as a return type, it is performing implicit type conversion. To avoid this and to obtain an error instead of an implicit conversion, we can simply enable a strict type, as follows:

<?php
declare(strict_types=1);
function add($num1, $num2):int{
    return ($num1+$num2);
}

echo add(2,4); //6
echo add(2.5,4); //Fatal error:  Uncaught TypeError: Return value of add() must be of the type integer, float returned

Null coalescing operator


The Null coalescing operator (??) is a syntactical sugar, but a important one. Previously in PHP5 when we were having some variable which could be undefined, we used the ternary operator as follows:

$username = isset($_GET['username']) ? $_GET['username'] : '';

However, now in PHP7, we can simply write:

$username = $_GET['username'] ?? '';

Although this is just a syntactical sugar, it can save time and make code cleaner.

Spaceship operator


The spaceship operator is also a shortcut comparison and is useful in user defined sorting functions. I am not going into detail about this, as it is already explained enough in its documentation: http://php.net/manual/en/migration70.new-features.php#migration70.new-features.spaceship-op.

Group use declarations


Classes, functions, and constants, which are in the same namespace, can now imported in a single use statement. Previously, multiple use statements were required for that. Here is an example to understand it better:

<?php
// use statement in Pre-PHP7 code
use abc\namespace\ClassA;
use abc\namespace\ClassB;
use abc\namespace\ClassC as C;

use function abc\namespace\funcA;
use function abc\namespace\funcB;
use function abc\namespace\funcC;

use const abc\namespace\ConstA;
use const abc\namespace\ConstB;
use const abc\namespace\ConstC;

// PHP 7+ code
use abc\namespace\{ClassA, ClassB, ClassC as C};
use function abc\namespace\{funcA, funcB, funcC};
use const abc\namespace\{ConstA, ConstB, ConstC};

As you can see from this example, how convenient the group use statement is, it is clearly visible. Curly braces with comma separated values are used to group values such as {classA, classB, classC as C}, resulting in the grouped use statement, instead of separately using...

Anonymous classes


Just like anonymous functions, now there anonymous classes in PHP. Note that if an object is required, then most probably we need some specific type of object and not just a random one, for example:

<?php
class App
{
    public function __construct()
    {
        //some code here
    }
}

function useApp(App $app)
{
    //use app somewhere
}

$app = new App();
useApp($app);

Note that a specific type of object was required in the useApp() function, and this type App couldn't be defined if it wasn't a class. So, where and why would we use an anonymous class with some specific functionality in it? We may need it in case we need to pass a class implementing some specific interface or extending some parent class, but only want to have this class used in one place. In that case, we can use an anonymous class. Here is the same example given in the PHP7 documentation so that it will be easy for you to follow up:

<?php
interface Logger {
    public function log(string $msg...

Closure::call()


Binding an object scope with a closure is an efficient way to use a closure with different objects. At the same time, it is also a simple way to use different closures having different behaviors an object in different places. This is because it binds the object scope with a closure at runtime without inheritance, composition, and so on. However, previously we didn't have the Closure::call() method; we had something like this:

<?php
// Pre PHP 7 code
class Point{
    private $x = 1; 
    private $y = 2;
}

$getXFn = function() {return $this->x;};
$getX = $getXFn->bindTo(new Point, 'Point');//intermediate closure
echo $getX(); // will output 1

But now with Closure::call(), the same code can be written as follows:

<?php
//  PHP 7+ code
class Point{
    private $x = 1; 
    private $y = 2;
}

// PHP 7+ code
$getX = function() {return $this->x;};
echo $getX->call(new Point); // outputs 1 as doing same thing

Both code snippets perform the same action. However, PHP7...

Errors and exceptions


In PHP7, most are now reported as exceptions. Only a few fatal errors halt script execution; otherwise, if you are carrying out error or exception handling, it will not halt the script. This is because now the Errors class implements a Throwable interface just like the Exception class, which also implements Throwable. So now, in most cases, fatal errors can be avoided through exception handling.

Here are some sub-classes of the error class:

  • TypeError
  • ParseError
  • ArithmeticError
    • DivisionByZeroError
  • AssertionError

This is how you can simply catch an error and handle it:

try {
    fn();
} catch(Throwable $error){
    echo $error->getMessage(); //Call to undefined function fn()
}

Here, $error->getMessage() is a method that is actually returning this message as a string. In our preceding example, the message will be similar to this: Call to undefined function fn().

This is not the only method you can use. Here is a list of methods that are defined in the Throwable interface...

PHP7.1


Till now, the preceding features that discussed were PHP7.0 related. However, the recent version of PHP7 is PHP7.1, so it is worth discussing the important features of PHP7.1 as well, at least the features which we will use, or features that are worth knowing and using somewhere in our work. In order to run the following code, you need to have PHP7.1 installed so, to do this, you can use the following commands:

sudo add-apt-repository ppa:ondrej/php
sudo apt-get update
(optional) sudo apt-get remove php7.0
sudo apt-get install php7.1 (from comments)

Remember that this is not an official upgrade path. The PPA is well-known, and is relatively safe to use.

Nullable types

If we are type hinting data types of parameters or types of function, then it is important that there should be a way to pass or return the NULL data type instead of type mentioning as parameter or return type. There can be different scenarios when we may need this, but what we need to do is place a ? before the data type...

More resources


We discussed new features of PHP7 and PHP 7.1 (recent version of PHP7) that we either found very important to discuss or which we are going to use in the rest of the book. However, we didn't discuss PHP7 features completely. You can find the features list on php.net: http://php.net/manual/en/migration70.new-features.php. Here, you can find the new features of PHP 7.1: http://php.net/manual/en/migration71.new-features.php.

Summary


In this chapter, we discussed important PHP7 features. Also, we covered new PHP7.1 features. This chapter covers the fundamentals which will be used in the rest of this book. Note that using PHP7 features is not necessary, but it helps us to write simplified code efficiently.

In the next chapter, we will start creating a RESTful API in PHP as we discussed in Chapter 1, RESTful Web Services, Introduction and Motivation, while utilizing some of the PHP7 features.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Building RESTful Web Services with PHP 7
Published in: Sep 2017Publisher: PacktISBN-13: 9781787127746
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Waheed ud din

Haafiz Waheed-ud-din Ahmad has been working in the IT industry since 2008. He has mostly worked in web application development and mostly used PHP at the server side. Although most of his experience is in PHP, he is a technology agnostic person and also likes to learn and adapt to new technologies. He also acts as an adviser for startups and new developers. He has worked on Python and JavaScript as well. He likes to experiment with new technologies, and he has also explored Golang, Scala, and Neo4J. He also has a keen interest in data science and big data domain and has worked on D3.js for data visualization. He is not just a technology enthusiast but also likes to solve day-to-day problems by the usage of technology. You can follow him on twitter at @Haafiz786.
Read more about Waheed ud din