Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
PHP 7 Programming Blueprints
PHP 7 Programming Blueprints

PHP 7 Programming Blueprints: Rethink PHP

Arrow left icon
Profile Icon Jose Palala Profile Icon Martin Helmich
Arrow right icon
€27.89 €30.99
eBook Oct 2016 320 pages 1st Edition
eBook
€27.89 €30.99
Paperback
€38.99
eBook + Subscription
€21.99 Monthly
Arrow left icon
Profile Icon Jose Palala Profile Icon Martin Helmich
Arrow right icon
€27.89 €30.99
eBook Oct 2016 320 pages 1st Edition
eBook
€27.89 €30.99
Paperback
€38.99
eBook + Subscription
€21.99 Monthly
eBook
€27.89 €30.99
Paperback
€38.99
eBook + Subscription
€21.99 Monthly

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
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

PHP 7 Programming Blueprints

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:

Creating views

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.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Don’t just learn PHP 7 – follow a diverse range of practical knowledge to get started quickly
  • Take advantage of PHP 7’s newest features – and find out how to use them to solve real development challenges
  • Put PHP to work for performance and scalability – we’ll show you how, you do it!

Description

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!

Who is this book for?

The book is for web developers, PHP consultants, and anyone who is working on multiple projects with PHP. Basic knowledge of PHP programming is assumed.

What you will learn

  • *Build versatile projects using the newest features PHP 7 has to offer
  • *Learn how to use PHP 7's event-driven asynchronous features
  • *Find out how to improve the performance of your code with effective techniques and design patterns
  • *Get to grips with backend development and find out how to optimize session handling
  • *Learn how to use the PHP 7 Abstract Syntax Tree to improve the quality of your code and make it more maintainable
  • *Find out how to build a RESTful web service
  • *Build your own asynchronous microservice

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 07, 2016
Length: 320 pages
Edition : 1st
Language : English
ISBN-13 : 9781785885242
Languages :

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
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Oct 07, 2016
Length: 320 pages
Edition : 1st
Language : English
ISBN-13 : 9781785885242
Languages :

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 155.97
PHP 7 Programming Blueprints
€38.99
PHP 7 Programming Cookbook
€41.99
PHP 7: Real World Application Development
€74.99
Total 155.97 Stars icon

Table of Contents

9 Chapters
1. Create a User Profile System and use the Null Coalesce Operator Chevron down icon Chevron up icon
2. Build a Database Class and Simple Shopping Cart Chevron down icon Chevron up icon
3. Building a Social Newsletter Service Chevron down icon Chevron up icon
4. Build a Simple Blog with Search Capability using Elasticsearch Chevron down icon Chevron up icon
5. Creating a RESTful Web Service Chevron down icon Chevron up icon
6. Building a Chat Application Chevron down icon Chevron up icon
7. Building an Asynchronous Microservice Architecture Chevron down icon Chevron up icon
8. Building a Parser and Interpreter for a Custom Language Chevron down icon Chevron up icon
9. Reactive Extensions in PHP Chevron down icon Chevron up icon
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.

Modal Close icon
Modal Close icon