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

Implementing a strategy pattern

It is often the case that runtime conditions force the developer to define several ways of doing the same thing. Traditionally, this involved a massive if/elseif/else block of commands. You would then either have to define large blocks of logic inside the if statement, or create a series of functions or methods to enable the different approaches. The strategy pattern attempts to formalize this process by having the primary class encapsulate a series of sub-classes that represent different approaches to solve the same problem.

How to do it...

  1. In this illustration, we will use the GetSet hydrator class defined previously as a strategy. We will define a primary Application\Generic\Hydrator\Any class, which will then consume strategy classes in the Application\Generic\Hydrator\Strategy namespace, including GetSet, PublicProps, and Extending.
  2. We first define class constants that reflect the built-in strategies that are available:
    namespace Application\Generic\Hydrator;
    use InvalidArgumentException;
    use Application\Generic\Hydrator\Strategy\ { 
    GetSet, PublicProps, Extending };
    class Any
    {
      const STRATEGY_PUBLIC  = 'PublicProps';
      const STRATEGY_GET_SET = 'GetSet';
      const STRATEGY_EXTEND  = 'Extending';
      protected $strategies;
      public $chosen;
  3. We then define a constructor that adds all built-in strategies to the $strategies property:
    public function __construct()
    {
      $this->strategies[self::STRATEGY_GET_SET] = new GetSet();
      $this->strategies[self::STRATEGY_PUBLIC] = new PublicProps();
      $this->strategies[self::STRATEGY_EXTEND] = new Extending();
    }
  4. We also add an addStrategy() method that allows us to overwrite or add new strategies without having to recode the class:
    public function addStrategy($key, HydratorInterface $strategy)
    {
      $this->strategies[$key] = $strategy;
    }
  5. The hydrate() and extract() methods simply call those of the chosen strategy:
    public function hydrate(array $array, $object)
    {
      $strategy = $this->chooseStrategy($object);
      $this->chosen = get_class($strategy);
      return $strategy::hydrate($array, $object);
    }
    
    public function extract($object)
    {
      $strategy = $this->chooseStrategy($object);
      $this->chosen = get_class($strategy);
      return $strategy::extract($object);
    }
  6. The tricky bit is figuring out which hydration strategy to choose. For this purpose we define chooseStrategy(), which takes an object as an argument. We first perform some detective work by way of getting a list of class methods. We then scan through the list to see if we have any getXXX() or setXXX() methods. If so, we choose the GetSet hydrator as our chosen strategy:
    public function chooseStrategy($object)
    {
      $strategy = NULL;
      $methodList = get_class_methods(get_class($object));
      if (!empty($methodList) && is_array($methodList)) {
          $getSet = FALSE;
          foreach ($methodList as $method) {
            if (preg_match('/^get|set.*$/i', $method)) {
                $strategy = $this->strategies[self::STRATEGY_GET_SET];
          break;
        }
      }
    }
  7. Still within our chooseStrategy() method, if there are no getters or setters, we next use get_class_vars() to determine if there are any available properties. If so, we choose PublicProps as our hydrator:
    if (!$strategy) {
        $vars = get_class_vars(get_class($object));
        if (!empty($vars) && count($vars)) {
            $strategy = $this->strategies[self::STRATEGY_PUBLIC];
        }
    }
  8. If all else fails, we fall back to the Extending hydrator, which returns a new class that simply extends the object class, thus making any public or protected properties available:
    if (!$strategy) {
        $strategy = $this->strategies[self::STRATEGY_EXTEND];
    }
    return $strategy;
    }
    }
  9. Now we turn our attention to the strategies themselves. First, we define a new Application\Generic\Hydrator\Strategy namespace.
  10. In the new namespace, we define an interface that allows us to identify any strategies that can be consumed by Application\Generic\Hydrator\Any:
    namespace Application\Generic\Hydrator\Strategy;
    interface HydratorInterface
    {
      public static function hydrate(array $array, $object);
      public static function extract($object);
    }
  11. The GetSet hydrator is exactly as defined in the previous two recipes, with the only addition being that it will implement the new interface:
    namespace Application\Generic\Hydrator\Strategy;
    class GetSet implements HydratorInterface
    {
    
      public static function hydrate(array $array, $object)
      {
        // defined in the recipe:
        // "Creating an Array to Object Hydrator"
      }
    
      public static function extract($object)
      {
        // defined in the recipe:
        // "Building an Object to Array Hydrator"
      }
    }
  12. The next hydrator simply reads and writes public properties:
    namespace Application\Generic\Hydrator\Strategy;
    class PublicProps implements HydratorInterface
    {
      public static function hydrate(array $array, $object)
      {
        $propertyList= array_keys(
          get_class_vars(get_class($object)));
        foreach ($propertyList as $property) {
          $object->$property = $array[$property] ?? NULL;
        }
        return $object;
      }
    
      public static function extract($object)
      {
        $array = array();
        $propertyList = array_keys(
          get_class_vars(get_class($object)));
        foreach ($propertyList as $property) {
          $array[$property] = $object->$property;
        }
        return $array;
      }
    }
  13. Finally, Extending, the Swiss Army knife of hydrators, extends the object class, thus providing direct access to properties. We further define magic getters and setters to provide access to properties.
  14. The hydrate() method is the most difficult as we are assuming no getters or setters are defined, nor are the properties defined with a visibility level of public. Accordingly, we need to define a class that extends the class of the object to be hydrated. We do this by first defining a string that will be used as a template to build the new class:
    namespace Application\Generic\Hydrator\Strategy;
    class Extending implements HydratorInterface
    {
      const UNDEFINED_PREFIX = 'undefined';
      const TEMP_PREFIX = 'TEMP_';
      const ERROR_EVAL = 'ERROR: unable to evaluate object';
      public static function hydrate(array $array, $object)
      {
        $className = get_class($object);
        $components = explode('\\', $className);
        $realClass  = array_pop($components);
        $nameSpace  = implode('\\', $components);
        $tempClass = $realClass . self::TEMP_SUFFIX;
        $template = 'namespace ' 
          . $nameSpace . '{'
          . 'class ' . $tempClass 
          . ' extends ' . $realClass . ' '
  15. Continuing in the hydrate() method, we define a $values property, and a constructor that assigns the array to be hydrated into the object as an argument. We loop through the array of values, assigning values to properties. We also define a useful getArrayCopy() method, which returns these values if needed, as well as a magic __get() method to simulate direct property access:
    . '{ '
    . '  protected $values; '
    . '  public function __construct($array) '
    . '  { $this->values = $array; '
    . '    foreach ($array as $key => $value) '
    . '       $this->$key = $value; '
    . '  } '
    . '  public function getArrayCopy() '
    . '  { return $this->values; } '
  16. For convenience we define a magic __get() method, which simulates direct variable access as if they were public:
    . '  public function __get($key) '
    . '  { return $this->values[$key] ?? NULL; } '
  17. Still in the template for the new class, we define also a magic __call() method, which simulates getters and setters:
    . '  public function __call($method, $params) '
    . '  { '
    . '    preg_match("/^(get|set)(.*?)$/i", '
    . '        $method, $matches); '
    . '    $prefix = $matches[1] ?? ""; '
    . '    $key    = $matches[2] ?? ""; '
    . '    $key    = strtolower(substr($key, 0, 1)) ' 
    . '              substr($key, 1); '
    . '    if ($prefix == "get") { '
    . '        return $this->values[$key] ?? NULL; '
    . '     } else { '
    . '        $this->values[$key] = $params[0]; '
    . '     } '
    . '  } '
    . '} '
    . '} // ends namespace ' . PHP_EOL
  18. Finally, still in the template for the new class, we add a function, in the global namespace, that builds and returns the class instance:
    . 'namespace { '
    . 'function build($array) '
    . '{ return new ' . $nameSpace . '\\' 
    .    $tempClass . '($array); } '
    . '} // ends global namespace '
    . PHP_EOL;
  19. Still in the hydrate() method, we execute the completed template using eval(). We then run the build() method defined just at the end of the template. Note that as we are unsure of the namespace of the class to be populated, we define and call build() from the global namespace:
    try {
        eval($template);
    } catch (ParseError $e) {
        error_log(__METHOD__ . ':' . $e->getMessage());
        throw new Exception(self::ERROR_EVAL);
    }
    return \build($array);
    }
  20. The extract() method is much easier to define as our choices are extremely limited. Extending a class and populating it from an array using magic methods is easily accomplished. The reverse is not the case. If we were to extend the class, we would lose all the property values, as we are extending the class, not the object instance. Accordingly, our only option is to use a combination of getters and public properties:
    public static function extract($object)
    {
      $array = array();
      $class = get_class($object);
      $methodList = get_class_methods($class);
      foreach ($methodList as $method) {
        preg_match('/^(get)(.*?)$/i', $method, $matches);
        $prefix = $matches[1] ?? '';
        $key    = $matches[2] ?? '';
        $key    = strtolower(substr($key, 0, 1)) 
        . substr($key, 1);
        if ($prefix == 'get') {
            $array[$key] = $object->$method();
        }
      }
      $propertyList= array_keys(get_class_vars($class));
      foreach ($propertyList as $property) {
        $array[$property] = $object->$property;
      }
      return $array;
      }
    }

How it works...

You can begin by defining three test classes with identical properties: firstName, lastName, and so on. The first, Person, should have protected properties along with getters and setters. The second, PublicPerson, will have public properties. The third, ProtectedPerson, has protected properties but no getters nor setters:

<?php
namespace Application\Entity;
class Person
{
  protected $firstName  = '';
  protected $lastName   = '';
  protected $address    = '';
  protected $city       = '';
  protected $stateProv  = '';
  protected $postalCode = '';
  protected $country    = '';
  
    public function getFirstName()
    {
      return $this->firstName;
    }

    public function setFirstName($firstName)
    {
      $this->firstName = $firstName;
    }

  // be sure to define remaining getters and setters

}

<?php
namespace Application\Entity;
class PublicPerson
{
  private $id = NULL;
  public $firstName  = '';
  public $lastName   = '';
  public $address    = '';
  public $city       = '';
  public $stateProv  = '';
  public $postalCode = '';
  public $country    = '';
}

<?php
namespace Application\Entity;

class ProtectedPerson
{
  private $id = NULL;
  protected $firstName  = '';
  protected $lastName   = '';
  protected $address    = '';
  protected $city       = '';
  protected $stateProv  = '';
  protected $postalCode = '';
  protected $country    = '';
}

You can now define a calling program called chap_11_strategy_pattern.php, which sets up autoloading and uses the appropriate classes:

<?php
require __DIR__ . '/../Application/Autoload/Loader.php';
Application\Autoload\Loader::init(__DIR__ . '/..');
use Application\Entity\ { Person, PublicPerson, ProtectedPerson };
use Application\Generic\Hydrator\Any;
use Application\Generic\Hydrator\Strategy\ { GetSet, Extending, PublicProps };

Next, create an instance of Person and run the setters to define values for properties:

$obj = new Person();
$obj->setFirstName('Li\'lAbner');
$obj->setLastName('Yokum');
$obj->setAddress('1 Dirt Street');
$obj->setCity('Dogpatch');
$obj->setStateProv('Kentucky');
$obj->setPostalCode('12345');
$obj->setCountry('USA');

Next, create an instance of the Any hydrator, call extract(), and use var_dump() to view the results:

$hydrator = new Any();
$b = $hydrator->extract($obj);
echo "\nChosen Strategy: " . $hydrator->chosen . "\n";
var_dump($b);

Observe, in the following output, that the GetSet strategy was chosen:

How it works...

Note

Note that the id property is not set as its visibility level is private.

Next, you can define an array with the same values. Call hydrate() on the Any instance, and supply a new PublicPerson instance as an argument:

$a = [
  'firstName'  => 'Li\'lAbner',
  'lastName'   => 'Yokum',
  'address'    => '1 Dirt Street',
  'city'       => 'Dogpatch',
  'stateProv'  => 'Kentucky',
  'postalCode' => '12345',
  'country'    => 'USA'
];

$p = $hydrator->hydrate($a, new PublicPerson());
echo "\nChosen Strategy: " . $hydrator->chosen . "\n";
var_dump($p);

Here is the result. Note that the PublicProps strategy was chosen in this case:

How it works...

Finally, call hydrate() again, but this time supply an instance of ProtectedPerson as the object argument. We then call getFirstName() and getLastName() to test the magic getters. We also access first and last names as direct variable access:

$q = $hydrator->hydrate($a, new ProtectedPerson());
echo "\nChosen Strategy: " . $hydrator->chosen . "\n";
echo "Name: {$q->getFirstName()} {$q->getLastName()}\n";
echo "Name: {$q->firstName} {$q->lastName}\n";
var_dump($q);

Here is the last output, showing that the Extending strategy was chosen. You'll also note that the instance is a new ProtectedPerson_TEMP class, and that the protected properties are fully populated:

How it works...