Home Web Development PHP 7 Programming Blueprints

PHP 7 Programming Blueprints

By Jose Palala , Martin Helmich
books-svg-icon Book
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Create a User Profile System and use the Null Coalesce Operator
About this book
When it comes to modern web development, performance is everything. The latest version of PHP has been improvised and updated to make it easier to build for performance, improved engine execution, better memory usage, and a new and extended set of tools. If you’re a web developer, what’s not to love? This guide will show you how to make full use of PHP 7 with a range of practical projects that will not only teach you the principles, but also show you how to put them into practice. It will push and extend your skills, helping you to become a more confident and fluent PHP developer. You’ll find out how to build a social newsletter service, a simple blog with a search capability using Elasticsearch, as well as a chat application. We’ll also show you how to create a RESTful web service, a database class to manage a shopping cart on an e-commerce site and how to build an asynchronous microservice architecture. With further guidance on using reactive extensions in PHP, we’re sure that you’ll find everything you need to take full advantage of PHP 7. So dive in now!
Publication date:
October 2016
Publisher
Packt
Pages
320
ISBN
9781785889714

 

Chapter 1.  Create a User Profile System and use the Null Coalesce Operator

To begin this chapter, let's check out the new null coalesce in PHP 7. We'll also learn how to build a simple profiles page with listed users that you can click on, and create a simple CRUD-like system which will enable us to register new users to the system and delete users for banning purposes.

We'll learn to use the PHP 7 null coalesce operator so that we can show data if there is any, or just display a simple message if there isn't any.

Let's create a simple UserProfile class. The ability to create classes has been available since PHP 5.

A class in PHP starts with the word class, and the name of the class:

class UserProfile { 
 
  private $table = 'user_profiles'; 
  
} 
 
} 

We've made the table private and added a private variable, where we define which table it will be related to.

Let's add two functions, also known as a method, inside the class to simply fetch the data from the database:

function fetch_one($id) { 
  $link = mysqli_connect(''); 
  $query = "SELECT * from ". $this->table . " WHERE `id` =' " .  $id "'"; 
  $results = mysqli_query($link, $query); 
} 
 
function fetch_all() { 
  $link = mysqli_connect('127.0.0.1', 'root','apassword','my_dataabase' ); 
  $query = "SELECT * from ". $this->table . "; 
 $results = mysqli_query($link, $query); 
} 
 

The null coalesce operator


We can use PHP 7's null coalesce operator to allow us to check whether our results contain anything, or return a defined text which we can check on the views, this will be responsible for displaying any data.

Let's put this in a file which will contain all the define statements, and call it:

//definitions.php 
define('NO_RESULTS_MESSAGE', 'No results found'); 
 
require('definitions.php'); 
function fetch_all() { 
   ...same lines ... 
   
   $results = $results ??  NO_RESULTS_MESSAGE; 
   return $message;    
} 

On the client side, we'll need to come up with a template to show the list of user profiles.

Let's create a basic HTML block to show that each profile can be a div element with several list item elements to output each table.

In the following function, we need to make sure that all values have been filled in with at least the name and the age. Then we simply return the entire string when the function is called:

function profile_template( $name, $age, $country ) { 
 $name = $name ?? null; 
  $age = $age ?? null; 
  if($name == null || $age === null) { 
    return 'Name or Age need to be set';  
   } else { 
 
    return '<div> 
 
         <li>Name: ' . $name . ' </li> 
 
         <li>Age: ' . $age . '</li> 
 
         <li>Country:  ' .  $country . ' </li> 
 
    </div>'; 
  } 
} 
 

Separation of Concerns


In a proper MVC architecture, we need to separate the view from the models that get our data, and the controllers will be responsible for handling business logic.

In our simple app, we will skip the controller layer since we just want to display the user profiles in one public facing page. The preceding function is also known as the template render part in an MVC architecture.

While there are frameworks available for PHP that use the MVC architecture out of the box, for now we can stick to what we have and make it work.

PHP frameworks can benefit a lot from the null coalesce operator. In some codes that I've worked with, we used to use the ternary operator a lot, but still had to add more checks to ensure a value was not falsy.

Furthermore, the ternary operator can get confusing, and takes some getting used to. The other alternative is to use the isSet function. However, due to the nature of the isSet function, some falsy values will be interpreted by PHP as being a set.

 

Creating views


Now that we have our model complete, a template render function, we just need to create the view with which we can look at each profile.

Our view will be put inside a foreach block, and we'll use the template we wrote to render the right values:

//listprofiles.php 
 
<html> 
<!doctype html> 
<head> 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> 
</head> 
<body> 
 
<?php 
foreach($results as $item) { 
  echo profile_template($item->name, $item->age, $item->country; 
} 
?> 
</body> 
</html> 

Let's put the code above into index.php .

While we may install the Apache server, configure it to run PHP, install new virtual hosts and the other necessary features, and put our PHP code into an Apache folder, this will take time. So, for the purposes of testing this out, we can just run PHP's server for development.

To run the built-in PHP server (read more at http://php.net/manual/en/features.commandline.webserver.php ) we will use the folder we are running, inside a terminal:

php -S localhost:8000

If we open up our browser, we should see nothing yet, No results found. This means we need to populate our database.

If you have an error with your database connection, be sure to replace the correct database credentials we supplied into each of the mysql_connect calls that we made.

  1. To supply data to our database, we can create a simple SQL script like this:

    INSERT INTO user_profiles ('Chin Wu', 30, 'Mongolia'); 
    INSERT INTO user_profiles ('Erik Schmidt', 22, 'Germany'); 
    INSERT INTO user_profiles ('Rashma Naru', 33, 'India'); 
    
  2. Let's save it in a file such as insert_profiles.sql. In the same directory as the SQL file, log on to the MySQL client by using the following command:

          mysql -u root -p
    
  3. Then type use <name of database>:

          mysql>  use <database>;
    
  4. Import the script by running the source command:

          mysql> source insert_profiles.sql
    

Now our user profiles page should show the following:

 

Create a profile input form


Now let's create the HTML form for users to enter their profile data.

Our profiles app would be no use if we didn't have a simple way for a user to enter their user profile details.

We'll create the profile input form like this:

//create_profile.php 
 
<html> 
<body> 
<form action="post_profile.php" method="POST"> 
 
  <label>Name</label><input name="name"> 
  <label>Age</label><input name="age"> 
  <label>Country</label><input name="country"> 
 
</form> 
</body> 
</html> 

In this profile post, we'll need to create a PHP script to take care of anything the user posts. It will create an SQL statement from the input values and output whether or not they were inserted.

We can use the null coalesce operator again to verify that the user has inputted all values and left nothing undefined or null:

$name = $_POST['name'] ?? ""; 
 
$age = $_POST['country'] ?? ""; 
 
$country = $_POST['country'] ?? ""; 

This prevents us from accumulating errors while inserting data into our database.

First, let's create a variable to hold each of the inputs in one array:

$input_values =  [ 
 'name' => $name, 
 'age' => $age, 
 'country' => $country 
]; 

The preceding code is a new PHP 5.4+ way to write arrays. In PHP 5.4+, it is no longer necessary to put an actual array(); the author personally likes the new syntax better.

We should create a new method in our UserProfile class to accept these values:

Class UserProfile { 
 
 public function insert_profile($values)  { 
 
 $link =  mysqli_connect('127.0.0.1', 'username','password', 'databasename'); 
 
 $q = " INSERT INTO " . $this->table . " VALUES ( '".$values['name']."', '".$values['age'] . "' ,'".$values['country']. "')"; 
   return mysqli_query($q); 
 
 } 
} 

Instead of creating a parameter in our function to hold each argument as we did with our profile template render function, we can simply use an array to hold our values.

This way, if a new field needs to be inserted into our database, we can just add another field to the SQL insert statement.

While we are at it, let's create the edit profile section.

For now, we'll assume that whoever is using this edit profile is the administrator of the site.

We'll need to create a page where, provided the $_GET['id'] has been set, that the user that we will be fetching from the database and displaying on the form. Here is how that code will look like:

<?php 
require('class/userprofile.php');//contains the class UserProfile into 
 
$id = $_GET['id'] ?? 'No ID'; 
//if id was a string, i.e. "No ID", this would go into the if block 
if(is_numeric($id)) { 
  $profile =  new UserProfile(); 
  //get data from our database 
  $results =   $user->fetch_id($id); 
  if($results && $results->num_rows > 0  ) { 
     while($obj = $results->fetch_object()) 
   { 
          $name = $obj->name; 
          $age = $obj->age; 
       $country = $obj->country; 
      } 
        //display form with a hidden field containing the value of the ID 
?> 
 
  <form action="post_update_profile.php" method="post"> 
    
  <label>Name</label><input name="name" value="<?=$name?>"> 
  <label>Age</label><input name="age" value="<?=$age?>"> 
  <label>Country</label><input name="country" value="<?=country?>"> 
 
</form> 
 
  <?php 
        
  } else { 
         exit('No such user'); 
  } 
   
} else { 
  echo $id; //this  should be No ID'; 
 exit; 
}   

Notice that we're using what is known as the shortcut echo statement in the form. It makes our code simpler and easier to read. Since we're using PHP 7, this feature should come out of the box.

Once someone submits the form, it goes into our $_POST variable and we'll create a new Update function in our UserProfile class.

 

Admin system


Let's finish off by creating a simple grid for an admin dashboard portal that will be used with our user profiles database. Our requirement for this is simple: we can just set up a table-based layout that displays each user profile in rows.

From the grid, we will add the links to be able to edit the profile, or delete it, if we want to. The code to display a table in our HTML view would look like this:

<table> 
 <tr> 
  <td>John Doe</td> 
  <td>21</td> 
  <td>USA</td> 
  <td><a href="edit_profile.php?id=1">Edit</a></td> 
  <td><a href="profileview.php?id=1">View</a> 
  <td><a href="delete_profile.php?id=1">Delete</a> 
 </tr> 
</table> 
This script to this is the following: 
//listprofiles.php 
$sql = "SELECT * FROM userprofiles LIMIT $start, $limit ";  
$rs_result = mysqli_query ($sql); //run the query 
 
while($row = mysqli_fetch_assoc($rs_result) { 
?> 
    <tr> 
           <td><?=$row['name'];?></td> 
           <td><?=$row['age'];?></td>  
        <td><?=$row['country'];?></td>       
 
         <td><a href="edit_profile.php?id=<?=$id?>">Edit</a></td> 
          <td><a href="profileview.php?id=<?=$id?>">View</a> 
          <td><a href="delete_profile.php?id=<?=$id?>">Delete</a> 
           </tr> 
 
<?php 
} 

There's one thing that we haven't yet created: A delete_profile.php page. The view and edit pages have been discussed already.

Here's how the delete_profile.php page would look:

<?php 
 
//delete_profile.php 
$connection = mysqli_connect('localhost','<username>','<password>', '<databasename>'); 
 
$id = $_GET['id'] ?? 'No ID'; 
 
if(is_numeric($id)) { 
mysqli_query( $connection, "DELETE FROM userprofiles WHERE id = '" .$id . "'"); 
} else { 
 echo $id; 
} 
i(!is_numeric($id)) {  
exit('Error: non numeric \$id');  
 } else { 
echo "Profile #" . $id . " has been deleted"; 
 
?> 

Of course, since we might have a lot of user profiles in our database, we have to create a simple pagination. In any pagination system, you just need to figure out the total number of rows and how many rows you want displayed per page. We can create a function that will be able to return a URL that contains the page number and how many to view per page.

From our queries database, we first create a new function for us to select only up to the total number of items in our database:

class UserProfile{ 
 // .... Etc ... 
function count_rows($table) { 
      $dbconn = new mysqli('localhost', 'root', 'somepass', 'databasename');  
  $query = $dbconn->query("select COUNT(*) as num from '". $table . "'"); 
 
   $total_pages = mysqli_fetch_array($query); 
 
   return $total_pages['num']; //fetching by array, so element 'num' = count 
} 

For our pagination, we can create a simple paginate function which accepts the base_url of the page where we have pagination, the rows per page - also known as the number of records we want each page to have - and the total number of records found:

require('definitions.php'); 
require('db.php'); //our database class 
 
Function paginate ($base_url, $rows_per_page, $total_rows) { 
  $pagination_links = array(); //instantiate an array to hold our html page links 
 
   //we can use null coalesce to check if the inputs are  null   
  ( $total_rows || $rows_per_page) ?? exit('Error: no rows per page and total rows);  
     //we exit with an error message if this function is called incorrectly  
     
    $pages =  $total_rows % $rows_per_page; 
    $i= 0; 
       $pagination_links[$i] =  "<a href="http://". $base_url  . "?pagenum=". $pagenum."&rpp=".$rows_per_page. ">"  . $pagenum . "</a>"; 
      } 
    return $pagination_links; 
 
} 

This function will help display the above page links in a table:

function display_pagination($links) {
      $display = '<div class="pagination">
                  <table><tr>';
      foreach ($links as $link) {
               echo "<td>" . $link . "</td>";
      }

       $display .= '</tr></table></div>';

       return $display;
    }

Notice that we're following the principle that there should rarely be any echo statements inside a function. This is because we want to make sure that other users of these functions are not confused when they debug some mysterious output on their page.

By requiring the programmer to echo out whatever the functions return, it becomes easier to debug our program. Also, we're following the Separation of Concerns, our code doesn't output the display, it just formats the display.

So any future programmer can just update the function's internal code and return something else. It also makes our function reusable; imagine that in the future someone uses our function, this way, they won't have to double check that there's some misplaced echo statement within our functions.

Tip

A note on alternative short tags

As you know, another way to echo is to use the <?= tag. You can use it like so: <?="helloworld"?>.These are known as short tags. In PHP 7, alternative PHP tags have been removed. The RFC states that <%, <%=, %> and <script language=php> have been deprecated. The RFC at https://wiki.php.net/rfc/remove_alternative_php_tags says that the RFC does not remove short opening tags (<?) or short opening tags with echo (<?=).

Since we have laid out the groundwork of creating paginate links, we now just have to invoke our functions. The following script is all that is needed to create a paginated page using the preceding function:

$mysqli = mysqli_connect('localhost','<username>','<password>', '<dbname>'); 
 
   $limit = $_GET['rpp'] ?? 10;    //how many items to show per page default 10; 
 
   $pagenum = $_GET['pagenum'];  //what page we are on 
 
   if($pagenum) 
     $start = ($pagenum - 1) * $limit; //first item to display on this page 
   else 
     $start = 0;                       //if no page var is given, set start to 0 
/*Display records here*/ 
$sql = "SELECT * FROM userprofiles LIMIT $start, $limit ";  
$rs_result = mysqli_query ($sql); //run the query 
 
while($row = mysqli_fetch_assoc($rs_result) { 
?> 
    <tr> 
           <td><?php echo $row['name']; ?></td> 
           <td><?php echo $row['age']; ?></td>  
        <td><?php echo $row['country']; ?></td>            
           </tr> 
 
<?php 
} 
 
/* Let's show our page */ 
/* get number of records through  */ 
   $record_count = $db->count_rows('userprofiles');  
 
$pagination_links =  paginate('listprofiles.php' , $limit, $rec_count); 
 echo display_pagination($paginaiton_links); 

The HTML output of our page links in listprofiles.php will look something like this:

<div class="pagination"><table> 
 <tr> 
        <td> <a href="listprofiles.php?pagenum=1&rpp=10">1</a> </td> 
         <td><a href="listprofiles.php?pagenum=2&rpp=10">2</a>  </td> 
        <td><a href="listprofiles.php?pagenum=3&rpp=10">2</a>  </td> 
    </tr> 
</table></div> 
 

Summary


As you can see, we have a lot of use cases for the null coalesce.

We learned how to make a simple user profile system, and how to use PHP 7's null coalesce feature when fetching data from the database, which returns null if there are no records. We also learned that the null coalesce operator is similar to a ternary operator, except this returns null by default if there is no data.

In the next chapter, we'll have more use cases for other PHP 7 features, especially when creating the database abstraction layer for use in our projects.

About the Authors
  • Jose Palala

    Jose Palala has been working professionally with PHP for at least 8 years. He has experience working with PHP frameworks such as Eden PHP, CodeIgniter, Laravel and Zend. He has worked for Philippine-based IT companies for at least 8 years, working on projects ranging from internal corporate systems and CMS websites. In his spare time, he regularly contributes back to the tech community in the Philippines.

    Browse publications by this author
  • Martin Helmich

    Martin Helmich studied computer science at the University of Applied Sciences in Osnabrück and lives in Rahden, Germany. He works as a software architect, specializing in building distributed applications using web technologies and Microservice Architectures. Besides programming in Go, PHP, Python, and Node.js, he also builds infrastructures using configuration management tools such as SaltStack and container technologies such as Docker and Kubernetes. He is an open source enthusiast and likes to make fun of people who are not using Linux. In his free time, you'll probably find him coding on one of his open source pet projects, listening to music, or reading science fiction literature.

    Browse publications by this author
Latest Reviews (4 reviews total)
The content is perfectly suited to my professional needs.
Haven't completed reading at this time.
bin zufrieden, habe noch nicht viel darin gelesen
PHP 7 Programming Blueprints
Unlock this book and the full library FREE for 7 days
Start now