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

Generating fake test data

Part of the testing and debugging process involves incorporating realistic test data. In some cases, especially when testing database access and producing benchmarks, large amounts of test data are needed. One way in which this can be accomplished is to incorporate a process of scraping data from websites, and then putting the data together in realistic, yet random, combinations to be inserted into a database.

How to do it...

  1. The first step is to determine what data is needed in order to test your application. Another consideration is dose the website address an international audience, or will the market be primarily from a single country?
  2. In order to produce a consistent fake data tool, it's extremely important to move the data from its source into a usable digital format. The first choice is a series of database tables. Another, not as attractive, alternative is a CSV file.
  3. You may end up converting the data in stages. For example, you could pull data from a web page that lists country codes and country names into a text file.
    How to do it...
  4. Since this list is short, it's easy to literally cut and paste this into a text file.
  5. We can then do a search for " " and replace with "\n", which gives us this:
    How to do it...
  6. This can then be imported into a spreadsheet, which then lets you export to a CSV file. From there, it's a simple matter to import it into a database. phpMyAdmin, for example, has such a facility.
  7. For the sake of this illustration, we will assume that we are generating data that will end up in the prospects table. Here is the SQL statement used to create this table:
    CREATE TABLE 'prospects' (
      'id' int(11) NOT NULL AUTO_INCREMENT,
      'first_name' varchar(128) NOT NULL,
      'last_name' varchar(128) NOT NULL,
      'address' varchar(256) DEFAULT NULL,
      'city' varchar(64) DEFAULT NULL,
      'state_province' varchar(32) DEFAULT NULL,
      'postal_code' char(16) NOT NULL,
      'phone' varchar(16) NOT NULL,
      'country' char(2) NOT NULL,
      'email' varchar(250) NOT NULL,
      'status' char(8) DEFAULT NULL,
      'budget' decimal(10,2) DEFAULT NULL,
      'last_updated' datetime DEFAULT NULL,
      PRIMARY KEY ('id'),
      UNIQUE KEY 'UNIQ_35730C06E7927C74' ('email')
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  8. Now it's time to create a class that is capable of generating fake data. We will then create methods to generate data for each of the fields shown above, except for id, which is auto-generated:
    namespace Application\Test;
    
    use PDO;
    use Exception;
    use DateTime;
    use DateInterval;
    use PDOException;
    use SplFileObject;
    use InvalidArgumentsException;
    use Application\Database\Connection;
    
    class FakeData
    {
      // data generation methods here
    }
  9. Next, we define constants and properties that will be used as part of the process:
    const MAX_LOOKUPS     = 10;
    const SOURCE_FILE     = 'file';
    const SOURCE_TABLE    = 'table';
    const SOURCE_METHOD   = 'method';
    const SOURCE_CALLBACK = 'callback';
    const FILE_TYPE_CSV   = 'csv';
    const FILE_TYPE_TXT   = 'txt';
    const ERROR_DB        = 'ERROR: unable to read source table';
    const ERROR_FILE      = 'ERROR: file not found';
    const ERROR_COUNT     = 'ERROR: unable to ascertain count or ID column missing';
    const ERROR_UPLOAD    = 'ERROR: unable to upload file';
    const ERROR_LOOKUP    = 'ERROR: unable to find any IDs in the source table';
    
    protected $connection;
    protected $mapping;
    protected $files;
    protected $tables;
  10. We then define properties that will be used to generate random letters, street names, and e-mail addresses. You can think of these arrays as seeds that can be modified and/or expanded to suite your needs. As an example, you might substitute street name fragments in Paris for a French audience:
    protected $alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    protected $street1 = ['Amber','Blue','Bright','Broad','Burning',
      'Cinder','Clear','Dewy','Dusty','Easy']; // etc. 
    protected $street2 = ['Anchor','Apple','Autumn','Barn','Beacon',
      'Bear','Berry','Blossom','Bluff','Cider','Cloud']; // etc.
    protected $street3 = ['Acres','Arbor','Avenue','Bank','Bend',
      'Canyon','Circle','Street'];
    protected $email1 = ['northern','southern','eastern','western',
      'fast','midland','central'];
    protected $email2 = ['telecom','telco','net','connect'];
    protected $email3 = ['com','net'];
  11. In the constructor, we accept a Connection object, used for database access, an array of mappings to the fake data:
    public function __construct(Connection $conn, array $mapping)
    {
      $this->connection = $conn;
      $this->mapping = $mapping;
    }
  12. To generate street names, rather than attempt to create a database table, it might be more efficient to use a set of seed arrays to generate random combinations. Here is an example of how this might work:
    public function getAddress($entry)
    {
      return random_int(1,999)
       . ' ' . $this->street1[array_rand($this->street1)]
       . ' ' . $this->street2[array_rand($this->street2)]
       . ' ' . $this->street3[array_rand($this->street3)];
    }
  13. Depending on the level of realism desired, you could also build a database table that matches postal codes to cities. Postal codes could also be randomly generated. Here is an example that generates postal codes for the UK:
    public function getPostalCode($entry, $pattern = 1)
    {
      return $this->alpha[random_int(0,25)]
       . $this->alpha[random_int(0,25)]
       . random_int(1, 99)
       . ' '
       . random_int(1, 9)
       . $this->alpha[random_int(0,25)]
       . $this->alpha[random_int(0,25)];
    }
  14. Fake e-mail generation can likewise use a set of seed arrays to produce random results. We could also program it to receive an existing $entry array, with parameters, and use those parameters to create the name portion of the address:
    public function getEmail($entry, $params = NULL)
    {
      $first = $entry[$params[0]] ?? $this->alpha[random_int(0,25)];
      $last  = $entry[$params[1]] ?? $this->alpha[random_int(0,25)];
      return $first[0] . '.' . $last
       . '@'
       . $this->email1[array_rand($this->email1)]
       . $this->email2[array_rand($this->email2)]
       . '.'
       . $this->email3[array_rand($this->email3)];
    }
  15. For date generation, one approach would be to accept as arguments an existing $entry array, with parameters. The parameters would be an array where the first value is a start date. The second parameter would be the maximum number of days to subtract from the start date. This effectively lets you return a random date from a range. Note that we use DateTime::sub() to subtract a random number of days. sub() requires a DateInterval instance, which we build using P, the random number of days, and then 'D':
    public function getDate($entry, $params)
    {
      list($fromDate, $maxDays) = $params;
      $date = new DateTime($fromDate);
      $date->sub(new DateInterval('P' . random_int(0, $maxDays) . 'D'));
      return $date->format('Y-m-d H:i:s');
    }
  16. As mentioned at the beginning of this recipe, the data sources we will use for fake data generation will vary. In some cases, as shown in the previous few steps, we use seed arrays, and build the fake data. In other cases, we might want to use a text or CSV file as a data source. Here is how such a method might look:
    public function getEntryFromFile($name, $type)
    {
      if (empty($this->files[$name])) {
          $this->pullFileData($name, $type);
      }
      return $this->files[$name][
      random_int(0, count($this->files[$name]))];
    }
  17. You will note that we first need to pull the file data into an array, which forms the return value. Here is the method that does that for us. We throw an Exception if the specified file is not found. The file type is identified as one of our class constants: FILE_TYPE_TEXT or FILE_TYPE_CSV. Depending on the type, we use either fgetcsv() or fgets():
    public function pullFileData($name, $type)
    {
      if (!file_exists($name)) {
          throw new Exception(self::ERROR_FILE);
      }
      $fileObj = new SplFileObject($name, 'r');
      if ($type == self::FILE_TYPE_CSV) {
          while ($data = $fileObj->fgetcsv()) {
            $this->files[$name][] = trim($data);
          }
      } else {
          while ($data = $fileObj->fgets()) {
            $this->files[$name][] = trim($data);
          }
      }
  18. Probably the most complicated aspect of this process is drawing random data from a database table. We accept as arguments the table name, the name of the column that comprises the primary key, an array that maps between the database column name in the lookup table, and the target column name:
    public function getEntryFromTable($tableName, $idColumn, $mapping)
    {
      $entry = array();
      try {
          if (empty($this->tables[$tableName])) {
            $sql  = 'SELECT ' . $idColumn . ' FROM ' . $tableName 
              . ' ORDER BY ' . $idColumn . ' ASC LIMIT 1';
            $stmt = $this->connection->pdo->query($sql);
            $this->tables[$tableName]['first'] = 
              $stmt->fetchColumn();
            $sql  = 'SELECT ' . $idColumn . ' FROM ' . $tableName 
              . ' ORDER BY ' . $idColumn . ' DESC LIMIT 1';
            $stmt = $this->connection->pdo->query($sql);
            $this->tables[$tableName]['last'] = 
              $stmt->fetchColumn();
        }
  19. We are now in a position to set up the prepared statement and initialize a number of critical variables:
    $result = FALSE;
    $count = self::MAX_LOOKUPS;
    $sql  = 'SELECT * FROM ' . $tableName 
      . ' WHERE ' . $idColumn . ' = ?';
    $stmt = $this->connection->pdo->prepare($sql);
  20. The actual lookup we place inside a do...while loop. The reason for this is that we need to run the query at least once to achieve results. Only if we do not arrive at a result do we continue with the loop. We generate a random number between the lowest ID and the highest ID, and then use this in a parameter in the query. Notice that we also decrement a counter to prevent an endless loop. This is in case the IDs are not sequential, in which case we could accidentally generate an ID that does not exist. If we exceed the maximum attempts, still with no results, we throw an Exception:
    do {
      $id = random_int($this->tables[$tableName]['first'], 
        $this->tables[$tableName]['last']);
      $stmt->execute([$id]);
      $result = $stmt->fetch(PDO::FETCH_ASSOC);
    } while ($count-- && !$result);
      if (!$result) {
          error_log(__METHOD__ . ':' . self::ERROR_LOOKUP);
          throw new Exception(self::ERROR_LOOKUP);
      }
    } catch (PDOException $e) {
        error_log(__METHOD__ . ':' . $e->getMessage());
        throw new Exception(self::ERROR_DB);
    }
  21. We then use the mapping array to retrieve values from the source table using keys expected in the destination table:
    foreach ($mapping as $key => $value) {
      $entry[$value] = $result[$key] ?? NULL;
    }
    return $entry;
    }
  22. The heart of this class is a getRandomEntry() method, which generates a single array of fake data. We loop through $mapping one entry at a time and examine the various parameters:
    public function getRandomEntry()
    {
      $entry = array();
      foreach ($this->mapping as $key => $value) {
        if (isset($value['source'])) {
          switch ($value['source']) {
  23. The source parameter is used to implement what effectively serves as a Strategy Pattern. We support four different possibilities for source, all defined as class constants. The first one is SOURCE_FILE. In this case, we use the getEntryFromFile() method discussed previously:
            case self::SOURCE_FILE :
                $entry[$key] = $this->getEntryFromFile(
                $value['name'], $value['type']);
              break;
  24. The callback option returns a value according to the callback supplied in the $mapping array:
            case self::SOURCE_CALLBACK :
                $entry[$key] = $value['name']();
              break;
  25. The SOURCE_TABLE option uses the database table defined in $mapping as a lookup. Note that getEntryFromTable(), discussed previously, is able to return an array of values, which means we need to use array_merge() to consolidate the results:
            case self::SOURCE_TABLE :
                $result = $this->getEntryFromTable(
                $value['name'],$value['idCol'],$value['mapping']);
                $entry = array_merge($entry, $result);
              break;
  26. The SOURCE_METHOD option, which is also the default, uses a method already included with this class. We check to see whether parameters are included, and, if so, add those to the method call. Note the use of {} to influence interpolation. If we made a $this->$value['name']() PHP 7 call, due to the Abstract Syntax Tree (AST) rewrite, it would interpolate like this, ${$this->$value}['name'](), which is not what we want:
            case self::SOURCE_METHOD :
            default :
              if (!empty($value['params'])) {
                  $entry[$key] = $this->{$value['name']}(
                    $entry, $value['params']);
              } else {
                  $entry[$key] = $this->{$value['name']}($entry);
              }
            }
        }
      }
      return $entry;
    }
  27. We define a method that loops through getRandomEntry() to produce multiple lines of fake data. We also add an option to insert to a destination table. If this option is enabled, we set up a prepared statement to insert, and also check to see whether we need to truncate any data currently in this table:
    public function generateData(
    $howMany, $destTableName = NULL, $truncateDestTable = FALSE)
    {
      try {
          if ($destTableName) {
            $sql = 'INSERT INTO ' . $destTableName
              . ' (' . implode(',', array_keys($this->mapping)) 
              . ') '. ' VALUES ' . ' (:' 
              . implode(',:', array_keys($this->mapping)) . ')';
            $stmt = $this->connection->pdo->prepare($sql);
            if ($truncateDestTable) {
              $sql = 'DELETE FROM ' . $destTableName;
              $this->connection->pdo->query($sql);
            }
          }
      } catch (PDOException $e) {
          error_log(__METHOD__ . ':' . $e->getMessage());
          throw new Exception(self::ERROR_COUNT);
      }
  28. Next, we loop through the number of lines of data requested, and run getRandomEntry(). If a database insert is requested, we execute the prepared statement in a try/catch block. In any event, we turn this method into a generator using the yield keyword:
    for ($x = 0; $x < $howMany; $x++) {
      $entry = $this->getRandomEntry();
      if ($insert) {
        try {
            $stmt->execute($entry);
        } catch (PDOException $e) {
            error_log(__METHOD__ . ':' . $e->getMessage());
            throw new Exception(self::ERROR_DB);
        }
      }
      yield $entry;
    }
    }

    Tip

    Best practice

    If the amount of data to be returned is massive, it's much better to yield the data as it is produced, thus saving the memory required for an array.

How it works...

The first thing to do is to ensure you have the data ready for random data generation. In this recipe, we will presume that the destination table is prospects, which has the following SQL database definition shown in step 7.

As a data source for names, you could create text files for first names and surnames. In this illustration, we will reference the data/files directory, and the files first_names.txt and surnames.txt. For city, state or province, postal code, and country, it might be useful to download the data from a source such as http://www.geonames.org/, and upload to a world_city_data table. For the remaining fields, such as address, e-mail, status, and so on, you could either use methods built into FakeData, or define callbacks.

Next, be sure to define Application\Test\FakeData, adding the content discussed in steps 8 to 29. After you have finished, create a calling program called chap_13_fake_data.php, which sets up autoloading and uses the appropriate classes. You should also define constants that match the path to the database configuration, and names files:

<?php
define('DB_CONFIG_FILE', __DIR__ . '/../config/db.config.php');
define('FIRST_NAME_FILE', __DIR__ . '/../data/files/first_names.txt');
define('LAST_NAME_FILE', __DIR__ . '/../data/files/surnames.txt');
require __DIR__ . '/../Application/Autoload/Loader.php';
Application\Autoload\Loader::init(__DIR__ . '/..');
use Application\Test\FakeData;
use Application\Database\Connection;

Next, define a mapping array that uses the column names in the destination table (prospects) as a key. You need to then define sub-keys for source, name, and any other parameters that are required. For starters, 'first_name' and 'last_name' will both use a file as a source, 'name' points to the name of the file, and 'type' indicates a file type of text:

$mapping = [
  'first_name'   => ['source' => FakeData::SOURCE_FILE,
  'name'         => FIRST_NAME_FILE,
  'type'         => FakeData::FILE_TYPE_TXT],
  'last_name'    => ['source' => FakeData::SOURCE_FILE,
  'name'         => LAST_NAME_FILE,
  'type'         => FakeData::FILE_TYPE_TXT],

The 'address', 'email', and 'last_updated' all use built-in methods as a data source. The last two also define parameters to be passed:

  'address'      => ['source' => FakeData::SOURCE_METHOD,
  'name'         => 'getAddress'],
  'email'        => ['source' => FakeData::SOURCE_METHOD,
  'name'         => 'getEmail',
  'params'       => ['first_name','last_name']],
  'last_updated' => ['source' => FakeData::SOURCE_METHOD,
  'name'         => 'getDate',
  'params'       => [date('Y-m-d'), 365*5]]

The 'phone', 'status' and 'budget' could all use callbacks to provide fake data:

  'phone'        => ['source' => FakeData::SOURCE_CALLBACK,
  'name'         => function () {
                    return sprintf('%3d-%3d-%4d', random_int(101,999),
                    random_int(101,999), random_int(0,9999)); }],
  'status'       => ['source' => FakeData::SOURCE_CALLBACK,
  'name'         => function () { $status = ['BEG','INT','ADV']; 
                    return $status[rand(0,2)]; }],
  'budget'       => ['source' => FakeData::SOURCE_CALLBACK,
                     'name' => function() { return random_int(0, 99999) 
                     + (random_int(0, 99) * .01); }]

And finally, 'city' draws its data from a lookup table, which also gives you data for the fields listed in the 'mapping' parameter. You can then leave those keys undefined. Notice that you should also specify the column representing the primary key for the table:

'city' => ['source' => FakeData::SOURCE_TABLE,
'name' => 'world_city_data',
'idCol' => 'id',
'mapping' => [
'city' => 'city', 
'state_province' => 'state_province',
'postal_code_prefix' => 'postal_code', 
'iso2' => 'country']
],
  'state_province'=> [],
  'postal_code'  => [],
  'country'    => [],
];

You can then define the destination table, a Connection instance, and create the FakeData instance. A foreach() loop will suffice to display a given number of entries:

$destTableName = 'prospects';
$conn = new Connection(include DB_CONFIG_FILE);
$fake = new FakeData($conn, $mapping);
foreach ($fake->generateData(10) as $row) {
  echo implode(':', $row) . PHP_EOL;
}

The output, for 10 rows, would look something like this:

How it works...

There's more...

Here is a summary of websites with various lists of data that could be of use when generating test data:

Type of Data

URL

Notes

Names

http://nameberry.com/

 
 

http://www.babynamewizard.com/international-names-lists-popular-names-from-around-the-world

 

Raw Name Lists

http://deron.meranda.us/data/census-dist-female-first.txt

US female first names

 

http://deron.meranda.us/data/census-dist-male-first.txt

US male first names

 

http://www.avss.ucsb.edu/NameFema.HTM

US female first names

 

http://www.avss.ucsb.edu/namemal.htm

US male first names

Last Names

http://names.mongabay.com/data/1000.html

US surnames from census

 

http://surname.sofeminine.co.uk/w/surnames/most-common-surnames-in-great-britain.html

British surnames

 

https://gist.github.com/subodhghulaxe/8148971

List of US surnames in the form of a PHP array

 

http://www.dutchgenealogy.nl/tng/surnames-all.php

Dutch surnames

 

http://www.worldvitalrecords.com/browsesurnames.aspx?l=A

International surnames; just change the last letter(s) to get a list of names starting with that letter(s)

Cities

http://www.travelgis.com/default.asp?framesrc=/cities/

World cities

 

https://www.maxmind.com/en/free-world-cities-database

 
 

https://github.com/David-Haim/CountriesToCitiesJSON

 
 

http://www.fallingrain.com/world/index.html

 

Postal Codes

https://boutell.com/zipcodes/

US only; includes cities, postal codes, latitude and longitude

 

http://www.geonames.org/export/

International; city names, postal codes, EVERYTHING!; free download