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 a generic form element generator

It's pretty easy to create a function that simply outputs a form input tag such as <input type="text" name="whatever" >. In order to make a form generator generically useful, however, we need to think about the bigger picture. Here are some other considerations over and above the basic input tag:

  • The form input tag and its associated HTML attributes
  • A label that tells the user what information they are entering
  • The ability to display entry errors following validation (more on that later!)
  • Some sort of wrapper, such as a <div> tag, or an HTML table <td> tag

How to do it...

  1. First, we define a Application\Form\Generic class. This will also later serve as a base class for specialized form elements:
    namespace Application\Form;
    
    class Generic
    {
      // some code ...
    }
  2. Next, we define some class constants, which will be generally useful in form element generation.
  3. The first three will become keys associated with the major components of a single form element. We then define supported input types and defaults:
    const ROW = 'row';
    const FORM = 'form';
    const INPUT = 'input';
    const LABEL = 'label';
    const ERRORS = 'errors';
    const TYPE_FORM = 'form';
    const TYPE_TEXT = 'text';
    const TYPE_EMAIL = 'email';
    const TYPE_RADIO = 'radio';
    const TYPE_SUBMIT = 'submit';
    const TYPE_SELECT = 'select';
    const TYPE_PASSWORD = 'password';
    const TYPE_CHECKBOX = 'checkbox';
    const DEFAULT_TYPE = self::TYPE_TEXT;
    const DEFAULT_WRAPPER = 'div';
  4. Next, we can define properties and a constructor that sets them.
  5. In this example, we require two properties, $name and $type, as we cannot effectively use the element without these attributes. The other constructor arguments are optional. Furthermore, in order to base one form element on another, we include a provision whereby the second argument, $type, can alternatively be an instance of Application\Form\Generic, in which case we simply run the getters (discussed later) to populate properties:
    protected $name;
    protected $type    = self::DEFAULT_TYPE;
    protected $label   = '';
    protected $errors  = array();
    protected $wrappers;
    protected $attributes;    // HTML form attributes
    protected $pattern =  '<input type="%s" name="%s" %s>';
    
    public function __construct($name, 
                    $type, 
                    $label = '',
                    array $wrappers = array(), 
                    array $attributes = array(),
                    array $errors = array())
    {
      $this->name = $name;
      if ($type instanceof Generic) {
          $this->type       = $type->getType();
          $this->label      = $type->getLabelValue();
          $this->errors     = $type->getErrorsArray();
          $this->wrappers   = $type->getWrappers();
          $this->attributes = $type->getAttributes();
      } else {
          $this->type       = $type ?? self::DEFAULT_TYPE;
          $this->label      = $label;
          $this->errors     = $errors;
          $this->attributes = $attributes;
          if ($wrappers) {
              $this->wrappers = $wrappers;
          } else {
              $this->wrappers[self::INPUT]['type'] =
                self::DEFAULT_WRAPPER;
              $this->wrappers[self::LABEL]['type'] = 
                self::DEFAULT_WRAPPER;
              $this->wrappers[self::ERRORS]['type'] = 
                self::DEFAULT_WRAPPER;
        }
      }
      $this->attributes['id'] = $name;
    }

    Note

    Note that $wrappers has three primary subkeys: INPUT, LABEL, and ERRORS. This allows us to define separate wrappers for labels, the input tag, and errors.

  6. Before defining the core methods that will produce HTML for the label, input tag, and errors, we should define a getWrapperPattern() method, which will produce the appropriate wrapping tags for the label, input, and error display.
  7. If, for example, the wrapper is defined as <div>, and its attributes include ['class' => 'label'], this method will return a sprintf() format pattern that looks like this: <div class="label">%s</div>. The final HTML produced for the label, for example, would then replace %s.
  8. Here is how the getWrapperPattern() method might look:
    public function getWrapperPattern($type)
    {
      $pattern = '<' . $this->wrappers[$type]['type'];
      foreach ($this->wrappers[$type] as $key => $value) {
        if ($key != 'type') {
          $pattern .= ' ' . $key . '="' . $value . '"';
        }
      }
      $pattern .= '>%s</' . $this->wrappers[$type]['type'] . '>';
      return $pattern;
    }
  9. We are now ready to define the getLabel() method. All this method needs to do is to plug the label into the wrapper using sprintf():
    public function getLabel()
    {
      return sprintf($this->getWrapperPattern(self::LABEL), 
                     $this->label);
    }
  10. In order to produce the core input tag, we need a way to assemble the attributes. Fortunately, this is easily accomplished as long as they are supplied to the constructor in the form of an associative array. All we need to do, in this case, is to define a getAttribs() method that produces a string of key-value pairs separated by a space. We return the final value using trim() to remove excess spaces.
  11. If the element includes either the value or href attribute, for security reasons we should escape the values on the assumption that they are, or could be, user-supplied (and therefore suspect). Accordingly, we need to add an if statement that checks and then uses htmlspecialchars() or urlencode():
    public function getAttribs()
    {
      foreach ($this->attributes as $key => $value) {
        $key = strtolower($key);
        if ($value) {
          if ($key == 'value') {
            if (is_array($value)) {
                foreach ($value as $k => $i) 
                  $value[$k] = htmlspecialchars($i);
            } else {
                $value = htmlspecialchars($value);
            }
          } elseif ($key == 'href') {
              $value = urlencode($value);
          }
          $attribs .= $key . '="' . $value . '" ';
        } else {
            $attribs .= $key . ' ';
        }
      }
      return trim($attribs);
    }
  12. For the core input tag, we split the logic into two separate methods. The primary method, getInputOnly(), produces only the HTML input tag. The second method, getInputWithWrapper(), produces the input embedded in a wrapper. The reason for the split is that when creating spin-off classes, such as a class to generate radio buttons, we will not need the wrapper:
    public function getInputOnly()
    {
      return sprintf($this->pattern, $this->type, $this->name, 
                     $this->getAttribs());
    }
    
    public function getInputWithWrapper()
    {
      return sprintf($this->getWrapperPattern(self::INPUT), 
                     $this->getInputOnly());
    }
  13. We now define a method that displays element validation errors. We will assume that the errors will be supplied in the form of an array. If there are no errors, we return an empty string. Otherwise, errors are rendered as <ul><li>error 1</li><li>error 2</li></ul> and so on:
    public function getErrors()
    {
      if (!$this->errors || count($this->errors == 0)) return '';
      $html = '';
      $pattern = '<li>%s</li>';
      $html .= '<ul>';
      foreach ($this->errors as $error)
      $html .= sprintf($pattern, $error);
      $html .= '</ul>';
      return sprintf($this->getWrapperPattern(self::ERRORS), $html);
    }
  14. For certain attributes, we might need more finite control over various aspects of the property. As an example, we might need to add a single error to the already existing array of errors. Also, it might be useful to set a single attribute:
    public function setSingleAttribute($key, $value)
    {
      $this->attributes[$key] = $value;
    }
    public function addSingleError($error)
    {
      $this->errors[] = $error;
    }
  15. Finally, we define getters and setters that allow us to retrieve or set the values of properties. For example, you might have noticed that the default value for $pattern is <input type="%s" name="%s" %s>. For certain tags (for example, select and form tags), we will need to set this property to a different value:
    public function setPattern($pattern)
    {
      $this->pattern = $pattern;
    }
    public function setType($type)
    {
      $this->type = $type;
    }
    public function getType()
    {
      return $this->type;
    }
    public function addSingleError($error)
    {
      $this->errors[] = $error;
    }
    // define similar get and set methods
    // for name, label, wrappers, errors and attributes
  16. We also need to add methods that will give the label value (not the HTML), as well as the errors array:
    public function getLabelValue()
    {
      return $this->label;
    }
    public function getErrorsArray()
    {
      return $this->errors;
    }

How it works...

Be sure to copy all the preceding code into a single Application\Form\Generic class. You can then define a chap_06_form_element_generator.php calling script that sets up autoloading and anchors the new class:

<?php
require __DIR__ . '/../Application/Autoload/Loader.php';
Application\Autoload\Loader::init(__DIR__ . '/..');
use Application\Form\Generic;

Next, define the wrappers. For illustration, we'll use HTML table data and header tags. Note that the label uses TH, whereas input and errors use TD:

$wrappers = [
  Generic::INPUT => ['type' => 'td', 'class' => 'content'],
  Generic::LABEL => ['type' => 'th', 'class' => 'label'],
  Generic::ERRORS => ['type' => 'td', 'class' => 'error']
];

You can now define an email element by passing parameters to the constructor:

$email = new Generic('email', Generic::TYPE_EMAIL, 'Email', $wrappers,
                    ['id' => 'email',
                     'maxLength' => 128,
                     'title' => 'Enter address',
                     'required' => '']);

Alternatively, define the password element using setters:

$password = new Generic('password', $email);
$password->setType(Generic::TYPE_PASSWORD);
$password->setLabel('Password');
$password->setAttributes(['id' => 'password',
                          'title' => 'Enter your password',
                          'required' => '']);

Lastly, be sure to define a submit button:

$submit = new Generic('submit', 
  Generic::TYPE_SUBMIT,
  'Login',
  $wrappers,
  ['id' => 'submit','title' => 'Click to login','value' => 'Click Here']);

The actual display logic might look like this:

<div class="container">
  <!-- Login Form -->
  <h1>Login</h1>
  <form name="login" method="post">
  <table id="login" class="display" 
    cellspacing="0" width="100%">
    <tr><?= $email->render(); ?></tr>
    <tr><?= $password->render(); ?></tr>
    <tr><?= $submit->render(); ?></tr>
    <tr>
      <td colspan=2>
        <br>
        <?php var_dump($_POST); ?>
      </td>
    </tr>
  </table>
  </form>
</div>

Here is the actual output:

How it works...