Table of Contents for
PHP 7: Real World Application Development

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition PHP 7: Real World Application Development by Branko Ajzele Published by Packt Publishing, 2016
  1. Cover
  2. Table of Contents
  3. PHP 7: Real World Application Development
  4. PHP 7: Real World Application Development
  5. PHP 7: Real World Application Development
  6. Credits
  7. Preface
  8. What you need for this learning path
  9. Who this learning path is for
  10. Reader feedback
  11. Customer support
  12. 1. Module 1
  13. 1. Building a Foundation
  14. PHP 7 installation considerations
  15. Using the built-in PHP web server
  16. Defining a test MySQL database
  17. Installing PHPUnit
  18. Implementing class autoloading
  19. Hoovering a website
  20. Building a deep web scanner
  21. Creating a PHP 5 to PHP 7 code converter
  22. 2. Using PHP 7 High Performance Features
  23. Understanding the abstract syntax tree
  24. Understanding differences in parsing
  25. Understanding differences in foreach() handling
  26. Improving performance using PHP 7 enhancements
  27. Iterating through a massive file
  28. Uploading a spreadsheet into a database
  29. Recursive directory iterator
  30. 3. Working with PHP Functions
  31. Developing functions
  32. Hinting at data types
  33. Using return value data typing
  34. Using iterators
  35. Writing your own iterator using generators
  36. 4. Working with PHP Object-Oriented Programming
  37. Developing classes
  38. Extending classes
  39. Using static properties and methods
  40. Using namespaces
  41. Defining visibility
  42. Using interfaces
  43. Using traits
  44. Implementing anonymous classes
  45. 5. Interacting with a Database
  46. Using PDO to connect to a database
  47. Building an OOP SQL query builder
  48. Handling pagination
  49. Defining entities to match database tables
  50. Tying entity classes to RDBMS queries
  51. Embedding secondary lookups into query results
  52. Implementing jQuery DataTables PHP lookups
  53. 6. Building Scalable Websites
  54. Creating a generic form element generator
  55. Creating an HTML radio element generator
  56. Creating an HTML select element generator
  57. Implementing a form factory
  58. Chaining $_POST filters
  59. Chaining $_POST validators
  60. Tying validation to a form
  61. 7. Accessing Web Services
  62. Converting between PHP and XML
  63. Creating a simple REST client
  64. Creating a simple REST server
  65. Creating a simple SOAP client
  66. Creating a simple SOAP server
  67. 8. Working with Date/Time and International Aspects
  68. Using emoticons or emoji in a view script
  69. Converting complex characters
  70. Getting the locale from browser data
  71. Formatting numbers by locale
  72. Handling currency by locale
  73. Formatting date/time by locale
  74. Creating an HTML international calendar generator
  75. Building a recurring events generator
  76. Handling translation without gettext
  77. 9. Developing Middleware
  78. Authenticating with middleware
  79. Using middleware to implement access control
  80. Improving performance using the cache
  81. Implementing routing
  82. Making inter-framework system calls
  83. Using middleware to cross languages
  84. 10. Looking at Advanced Algorithms
  85. Using getters and setters
  86. Implementing a linked list
  87. Building a bubble sort
  88. Implementing a stack
  89. Building a binary search class
  90. Implementing a search engine
  91. Displaying a multi-dimensional array and accumulating totals
  92. 11. Implementing Software Design Patterns
  93. Creating an array to object hydrator
  94. Building an object to array hydrator
  95. Implementing a strategy pattern
  96. Defining a mapper
  97. Implementing object-relational mapping
  98. Implementing the Pub/Sub design pattern
  99. 12. Improving Web Security
  100. Filtering $_POST data
  101. Validating $_POST data
  102. Safeguarding the PHP session
  103. Securing forms with a token
  104. Building a secure password generator
  105. Safeguarding forms with a CAPTCHA
  106. Encrypting/decrypting without mcrypt
  107. 13. Best Practices, Testing, and Debugging
  108. Using Traits and Interfaces
  109. Universal exception handler
  110. Universal error handler
  111. Writing a simple test
  112. Writing a test suite
  113. Generating fake test data
  114. Customizing sessions using session_start parameters
  115. A. Defining PSR-7 Classes
  116. Implementing PSR-7 value object classes
  117. Developing a PSR-7 Request class
  118. Defining a PSR-7 Response class
  119. 2. Module 2
  120. 1. Setting Up the Environment
  121. Setting up Debian or Ubuntu
  122. Setting up CentOS
  123. Setting up Vagrant
  124. Summary
  125. 2. New Features in PHP 7
  126. New operators
  127. Uniform variable syntax
  128. Miscellaneous features and changes
  129. Summary
  130. 3. Improving PHP 7 Application Performance
  131. HTTP server optimization
  132. HTTP persistent connection
  133. Content Delivery Network (CDN)
  134. CSS and JavaScript optimization
  135. Full page caching
  136. Varnish
  137. The infrastructure
  138. Summary
  139. 4. Improving Database Performance
  140. Storage engines
  141. The Percona Server - a fork of MySQL
  142. MySQL performance monitoring tools
  143. Percona XtraDB Cluster (PXC)
  144. Redis – the key-value cache store
  145. Memcached key-value cache store
  146. Summary
  147. 5. Debugging and Profiling
  148. Profiling with Xdebug
  149. PHP DebugBar
  150. Summary
  151. 6. Stress/Load Testing PHP Applications
  152. ApacheBench (ab)
  153. Siege
  154. Load testing real-world applications
  155. Summary
  156. 7. Best Practices in PHP Programming
  157. Test-driven development (TDD)
  158. Design patterns
  159. Service-oriented architecture (SOA)
  160. Being object-oriented and reusable always
  161. PHP frameworks
  162. Version control system (VCS) and Git
  163. Deployment and Continuous Integration (CI)
  164. Summary
  165. A. Tools to Make Life Easy
  166. Git – A version control system
  167. Grunt watch
  168. Summary
  169. B. MVC and Frameworks
  170. Laravel
  171. Lumen
  172. Apigility
  173. Summary
  174. 3. Module 3
  175. 1. Ecosystem Overview
  176. Summary
  177. 2. GoF Design Patterns
  178. Structural patterns
  179. Behavioral patterns
  180. Summary
  181. 3. SOLID Design Principles
  182. Open/closed principle
  183. Liskov substitution principle
  184. Interface Segregation Principle
  185. Dependency inversion principle
  186. Summary
  187. 4. Requirement Specification for a Modular Web Shop App
  188. Wireframing
  189. Defining a technology stack
  190. Summary
  191. 5. Symfony at a Glance
  192. Creating a blank project
  193. Using Symfony console
  194. Controller
  195. Routing
  196. Templates
  197. Forms
  198. Configuring Symfony
  199. The bundle system
  200. Databases and Doctrine
  201. Testing
  202. Validation
  203. Summary
  204. 6. Building the Core Module
  205. Dependencies
  206. Implementation
  207. Unit testing
  208. Functional testing
  209. Summary
  210. 7. Building the Catalog Module
  211. Dependencies
  212. Implementation
  213. Unit testing
  214. Functional testing
  215. Summary
  216. 8. Building the Customer Module
  217. Dependencies
  218. Implementation
  219. Unit testing
  220. Functional testing
  221. Summary
  222. 9. Building the Payment Module
  223. Dependencies
  224. Implementation
  225. Unit testing
  226. Functional testing
  227. Summary
  228. 10. Building the Shipment Module
  229. Dependencies
  230. Implementation
  231. Unit testing
  232. Functional testing
  233. Summary
  234. 11. Building the Sales Module
  235. Dependencies
  236. Implementation
  237. Unit testing
  238. Functional testing
  239. Summary
  240. 12. Integrating and Distributing Modules
  241. Understanding GitHub
  242. Understanding Composer
  243. Understanding Packagist
  244. Summary
  245. Bibliography
  246. Index

Creating an HTML international calendar generator

Creating a program to display a calendar is something you would most likely do as a student at secondary school. A nested for() loop, where the inside loop generates a list of seven days, will generally suffice. Even the problem of how many days there are in the month is easily solved in the form of a simple array. Where it starts to get tricky is when you need to figure out, for any given year, on what day of the week does the 1st of January fall. Also, what if you want to represent the months and days of the week in a language and format acceptable to a specific locale? As you have probably guessed, we will build a solution using the previously discussed Application\I18n\Locale class.

How to do it...

  1. First we need to create a generic class that will hold information for a single day. Initially it will only hold an integer value, $dayOfMonth. Later, in the next recipe, we'll expand it to include events. As the primary purpose of this class will be to yield $dayOfMonth, we'll incorporate this value into its constructor, and define __invoke() to return this value as well:
    namespace Application\I18n;
    
    class Day
    {
      public $dayOfMonth;
      public function __construct($dayOfMonth)
      {
        $this->dayOfMonth = $dayOfMonth;
      }
      public function __invoke()
      {
        return $this->dayOfMonth ?? '';
      }
    }
  2. Create a new class that will hold the appropriate calendar-generation methods. It will accept an instance of Application\I18n\Locale, and will define a couple of class constants and properties. The format codes, such as EEEEE and MMMM, are drawn from ICU date formats:
    namespace Application\I18n;
    
    use IntlCalendar;
    
    class Calendar
    {
    
      const DAY_1 = 'EEEEE';  // T
      const DAY_2 = 'EEEEEE'; // Tu
      const DAY_3 = 'EEE';   // Tue
      const DAY_FULL = 'EEEE'; // Tuesday
      const MONTH_1 = 'MMMMM'; // M
      const MONTH_3 = 'MMM';  // Mar
      const MONTH_FULL = 'MMMM';  // March
      const DEFAULT_ACROSS = 3;
      const HEIGHT_FULL = '150px';
      const HEIGHT_SMALL = '60px';
    
      protected $locale;
      protected $dateFormatter;
      protected $yearArray;
      protected $height;
    
      public function __construct(Locale $locale)
      {
        $this->locale = $locale;
      }
    
         // other methods are discussed in the following bullets
    
    }
  3. Then we define a method that returns an IntlDateFormatter instance from our locale class. This is stored in a class property, as it will be used frequently:
    protected function getDateFormatter()
    {
     if (!$this->dateFormatter) {
      $this->dateFormatter = $this->locale->getDateFormatter(Locale::DATE_TYPE_FULL);
     }
     return $this->dateFormatter;
    }
  4. Next we define a core method, buildMonthArray(), which creates a multi-dimensional array where the outer key is the week of the year, and the inner array is seven elements representing the days of the week. We accept the year, month, and optional time zone as arguments. Note, as part of variable initialization, we subtract 1 from the month. This is because the IntlCalendar::set() method expects a 0-based value for the month, where 0 represents January, 1 is February, and so on:
    public function buildMonthArray($year, $month, $timeZone = NULL)
    {
    $month -= 1; 
    //IntlCalendar months are 0 based; Jan==0, Feb==1 and so on
      $day = 1;
      $first = TRUE;
      $value = 0;
      $monthArray = array();
  5. We then create an IntlCalendar instance, and use it to determine how many days are in this month:
    $cal = IntlCalendar::createInstance($timeZone, $this->locale->getLocaleCode());
    $cal->set($year, $month, $day);
    $maxDaysInMonth = $cal->getActualMaximum(IntlCalendar::FIELD_DAY_OF_MONTH);
  6. After that we use our IntlDateFormatter instance to determine what day of the week equates to the 1st of this month. After that, we set the pattern to w, which will subsequently give us the week number:
    $formatter = $this->getDateFormatter();
    $formatter->setPattern('e');
    $firstDayIsWhatDow = $formatter->format($cal);
  7. We are now ready to loop through all days in the month with nested loops. An outer while() loop ensures we don't go past the end of the month. The inner loop represents the days of the week. You will note that we take advantage of IntlCalendar::get(), which allows us to retrieve values from a wide range of predefined fields. We also adjust the week of the year value to 0 if it exceeds 52:
    while ($day <= $maxDaysInMonth) {
      for ($dow = 1; $dow <= 7; $dow++) {
        $cal->set($year, $month, $day);
        $weekOfYear = $cal->get(IntlCalendar::FIELD_WEEK_OF_YEAR);
        if ($weekOfYear > 52) $weekOfYear = 0;
  8. We then check to see whether $first is still set TRUE. If so, we start adding day numbers to the array. Otherwise, the array value is set to NULL. We then close all open statements and return the array. Note that we also need to make sure the inner loop doesn't go past the number of days in the month, hence the extra if() statement in the outer else clause.

    Note

    Note that instead of just storing the value for the day of the month, we use the newly defined Application\I18n\Day class.

          if ($first) {
            if ($dow == $firstDayIsWhatDow) {
              $first = FALSE;
              $value = $day++;
            } else {
              $value = NULL;
            }
          } else {
            if ($day <= $maxDaysInMonth) {
              $value = $day++;
            } else {
              $value = NULL;
            }
          }
          $monthArray[$weekOfYear][$dow] = new Day($value);
        }
      }
      return $monthArray;
    }

Refining internationalized output

  1. First, a series of small methods, starting with one that extracts the internationally formatted day based on type. The type determines whether we deliver the full name of the day, an abbreviation, or just a single letter, all appropriate for that locale:
    protected function getDay($type, $cal)
    {
      $formatter = $this->getDateFormatter();
      $formatter->setPattern($type);
      return $formatter->format($cal);
    }
  2. Next we need a method that returns an HTML row of day names, calling the newly defined getDay() method. As mentioned previous, the type dictates the appearance of the days:
    protected function getWeekHeaderRow($type, $cal, $year, $month, $week)
    {
      $output = '<tr>';
      $width  = (int) (100/7);
      foreach ($week as $day) {
        $cal->set($year, $month, $day());
        $output .= '<th style="vertical-align:top;" width="' . $width . '%">' . $this->getDay($type, $cal) . '</th>';
      }
      $output .= '</tr>' . PHP_EOL;
      return $output;
    }
  3. After that, we define a very simple method to return a row of week dates. Note that we take advantage of Day::__invoke() using: $day():
    protected function getWeekDaysRow($week)
    {
      $output = '<tr style="height:' . $this->height . ';">';
      $width  = (int) (100/7);
      foreach ($week as $day) {
        $output .= '<td style="vertical-align:top;" width="' . $width . '%">' . $day() .  '</td>';
      }
      $output .= '</tr>' . PHP_EOL;
      return $output;
    }
  4. And finally, a method that puts the smaller methods together to generate a calendar for a single month. First we build the month array, but only if $yearArray is not already available:
    public function calendarForMonth($year, 
        $month, 
        $timeZone = NULL, 
        $dayType = self::DAY_3, 
        $monthType = self::MONTH_FULL, 
        $monthArray = NULL)
    {
      $first = 0;
      if (!$monthArray) 
        $monthArray = $this->yearArray[$year][$month]
        ?? $this->buildMonthArray($year, $month, $timeZone);
  5. The month needs to be decremented by 1 as IntlCalendar months are 0-based: Jan = 0, Feb = 1, and so on. We then build an IntlCalendar instance using the time zone (if any), and the locale. We next create a IntlDateFormatter instance to retrieve the month name and other information according to locale:
      $month--;
      $cal = IntlCalendar::createInstance($timeZone, $this->locale->getLocaleCode());
      $cal->set($year, $month, 1);
      $formatter = $this->getDateFormatter();
      $formatter->setPattern($monthType);
  6. We then loop through the month array, and call the smaller methods just mentioned to build the final output:
      $this->height = ($dayType == self::DAY_FULL) 
         ? self::HEIGHT_FULL : self::HEIGHT_SMALL;
      $html = '<h1>' . $formatter->format($cal) . '</h1>';
      $header = '';
      $body   = '';
      foreach ($monthArray as $weekNum => $week) {
        if ($first++ == 1) {
          $header .= $this->getWeekHeaderRow($dayType, $cal, $year, $month, $week);
        }
        $body .= $this->getWeekDaysRow($dayType, $week);
      }
      $html .= '<table>' . $header . $body . '</table>' . PHP_EOL;
      return $html;
    }
  7. In order to generate a calendar for the entire year, it's a simple matter of looping through months 1 to 12. To facilitate outside access, we first define a method that builds a year array:
    public function buildYearArray($year, $timeZone = NULL)
    {
      $this->yearArray = array();
      for ($month = 1; $month <= 12; $month++) {
        $this->yearArray[$year][$month] = $this->buildMonthArray($year, $month, $timeZone);
      }
      return $this->yearArray;
    }
    
    public function getYearArray()
    {
      return $this->yearArray;
    }
  8. To generate a calendar for a year, we define a method, calendarForYear(). If the year array has not been build, we call buildYearArray(). We take into account how many monthly calendars we wish to display across and then call calendarForMonth():
    public function calendarForYear($year, 
      $timeZone = NULL, 
      $dayType = self::DAY_1, 
      $monthType = self::MONTH_3, 
      $across = self::DEFAULT_ACROSS)
    {
      if (!$this->yearArray) $this->buildYearArray($year, $timeZone);
      $yMax = (int) (12 / $across);
      $width = (int) (100 / $across);
      $output = '<table>' . PHP_EOL;
      $month = 1;
      for ($y = 1; $y <= $yMax; $y++) {
        $output .= '<tr>';
        for ($x = 1; $x <= $across; $x++) {
          $output .= '<td style="vertical-align:top;" width="' . $width . '%">' . $this->calendarForMonth($year, $month, $timeZone, $dayType, $monthType, $this->yearArray[$year][$month++]) . '</td>';
        }
        $output .= '</tr>' . PHP_EOL;
      }
      $output .= '</table>';
      return $output;
    }

How it works...

First of all, make sure you build the Application\I18n\Locale class as defined in the previous recipe. After that, create a new file, Calendar.php, in the Application\I18n folder, with all the methods described in this recipe.

Next, define a calling program, chap_08_html_calendar.php, which sets up autoloading and creates Locale and Calendar instances. Also be sure to define the year and month:

<?php
require __DIR__ . '/../Application/Autoload/Loader.php';
Application\Autoload\Loader::init(__DIR__ . '/..');
use Application\I18n\Locale;
use Application\I18n\Calendar;

$localeFr = new Locale('fr-FR');
$localeUs = new Locale('en_US');
$localeTh = new Locale('th_TH');
$calendarFr = new Calendar($localeFr);
$calendarUs = new Calendar($localeUs);
$calendarTh = new Calendar($localeTh);
$year = 2016;
$month = 1;
?>

You can then develop appropriate view logic to display the different calendars. For example, you can include parameters to display the full month and day names:

<!DOCTYPE html>
<html>
  <head>
  <title>PHP 7 Cookbook</title>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <link rel="stylesheet" type="text/css" href="php7cookbook_html_table.css">
  </head>
  <body>
    <h3>Year: <?= $year ?></h3>
    <?= $calendarFr->calendarForMonth($year, $month, NULL, Calendar::DAY_FULL); ?>
    <?= $calendarUs->calendarForMonth($year, $month, NULL, Calendar::DAY_FULL); ?>
    <?= $calendarTh->calendarForMonth($year, $month, NULL, Calendar::DAY_FULL); ?>
  </body>
</html>
How it works...

With a couple of modifications, you can also display a calendar for the entire year:

$localeTh = new Locale('th_TH');
$localeEs = new Locale('es_ES');
$calendarTh = new Calendar($localeTh);
$calendarEs = new Calendar($localeEs);
$year = 2016;
echo $calendarTh->calendarForYear($year);
echo $calendarEs->calendarForYear($year);

Here is the browser output showing a full year calendar in Spanish:

How it works...

See also