PHP Wants To Be Your Web Language Of The Future – Part 1 – Generators

PHP GeneratorsThis is part 1 of a 6 part series looking at the some of the wonderful features of PHP 5.5 and why it might remain a dominate web language for the future. This series was originally written for the Software Developer’s Journal.

Back in the early days of PHP the language was very different than it is today. While classes were available, PHP itself was very fragmented and felt more like a library of functions than a cohesive language. After all, PHP was originally set up for templating not pulling complex systems together. It felt more like Perl or a web based scripting utility language that was the glue for a larger system than being the focus of the system itself. Need a simple script to move some files? PHP could do it. Need a script for parsing a simple text file? PHP could do that too. Need a full fledge ecommerce solution handling thousands of transactions a day? Well perhaps you should look to Active Server Pages (ASP) or Java Server Pages (JSP) because PHP was slow and just not robust enough to handle an end-to-end solution.

PHP did have a few things going for it however. It was fun to use, easy enough to learn and was not as verbose as some of the other languages out there. It was close enough to Perl to get Perl people on board, came from C++ style syntax to get the desktop developers into trying it and had a flair for fixing those problems that web developers had at the time… needing something server-side, dynamic and could conjure up “magic”. We developers like “magic”.

As PHP progressed through the early part of this millennium it grew popular with newbies wanting to develop dynamic web pages. This was a blessing as well as a curse. It helped people get more interested in developing for the web, like yours truly, but it also allowed for new developers to create code that worked even if it lacked proper design. Why separate out the PHP from your HTML when you could just copy and paste a line of code into your page and get the desired effect? This mentality lead to a lot of web content out there, and still being generated even today, that is inefficient and often dangerous. The type of code open to SQL injections, using improper input sanitation and simply hacked together.

The lack of restrictions and rules around proper system design has lead to many well publicized website hacks. These reports have given the language itself a bit of a nasty taste to most developers. So next time you ask a question about PHP and you get some old hat veteran replying about how PHP is weak and lacks security don’t believe them. It might have been the case in the past, but today it just isn’t true. PHP is strong and has a huge user base working on its future. I would argue that PHP’s weakest link is humans with their bad coding practices.

PHP Is Now Solving Real Problems

Fast forward a bit to the PHP 5.x branch and things have changed quite a bit. Over the last several years the PHP community has been working on bringing PHP up to a place where it could be a leading language on the web. PHP 5 has introduced mechanisms popular to many desktop and functional based languages including exception handling with try catches, defining explicit constructors and destructors, increased inheritance related functionality, interfaces as well as traits and many constructs that simplify syntax and remove boilerplate (which PHP 5.5 continues to do). It has also focused on issues around performance (with things like Opcache) and locking down security with bound parameters to help prevent SQL injection (phasing out MySQL functions in the process in favor of MySQLi and PDO).

With these significant upgrades PHP 5.x has really grown and matured into a language that is becoming the cornerstone for several high level projects like WordPress, Joomla, Facebook and many enterprise projects. For example, just last month I built an application tying an online ordering form into our instance of Sugar CRM with relative ease (which is also built in PHP btw). PHP has become the backend script for feeding news results to tickers, generating data to HTML5 dashboards and providing historical pricing to dynamic graphs.

These large scale applications have also fueled the continued growth for PHP development related jobs. Go to any tech related job board (like freelancer.com) and look up how many jobs are being offered out there for someone who knows PHP. The problems are out there and PHP continues to solve them. It has grown into one of my favorite languages by far and the number one language I recommend for web server-side development. All this and it is still as easy to learn as ever, perfect for someone looking to learn their first web based server-side language.

PHP 5.5 Focuses on Saving Time and Sanity

I have mentioned earlier that the 5.x branch has made tremendous strides in rounding out the language into something a little more robust. From my point of view it has focused on three major pillars. First is simplifying syntax through new constructs like the foreach or list(). The second pillar is increased security to protect the user like developing stronger password management and encryption. The last pillar is improved performance to power the most demanding web applications. So where does PHP 5.5’s new features fit into this grand three pillar design?

Generators

One thing to get straight, generators are purely “syntax sugar” to simplify many processes and, at most, save a bit of memory. This feature fits into the grand scheme of making constructs simpler to use and reduce syntax boilerplate. All these examples I show you below could be done in other ways using PHP. A few ways might be through a callback or a recursive function or perhaps even a simple design pattern like a factory. The real power of generators comes by making iteration simple and straightforward without the need for a ton of iterator scaffolding code.

Generators start with a simple function that returns a forward only generator class. A generator class can be used in a foreach to iterate over; much like you can iterate over an array. Where you would use an array in a foreach, you would use your generator instead. Here is a simple example.

// Example using an array…
foreach ($my_array as $value) {
   echo “$value<br/>”;
}

// Example using a generator…
foreach (getValues() as $value) {
   echo “$value<br/>”;
}

The only difference here is that getValues() is a function which returns a generator object, able to be iterated over. Through each pass of the foreach, getValues() is called and a value in that function is yielded to the caller. The yielded value is then placed into our variable which we have called $value. When the function ceases to yield a value the foreach completes. Where something like this works out great is when we need to generate a list of values that may or may not have an actual limit. I don’t have to store 10,000 values in an array, consuming memory, to then iterate over. The generator can generate those values on-the-fly and never actually have to take storage space. This makes it perfect for generating a series like the Gregory–Leibniz series for finding PI. The series continues forever but with each iteration we get closer to yielding an accurate representation of PI. Below is an example of how we might do that using a generator we will call calcPI().

<?php

  // calcPI generates, or “yields”, approximations for PI
  // for as long as we call it.
  function calcPI($iterations) {
    $sign = 1;
    $denom = 1;
    $sum = 0;

    for ($i = 0; $i < $iterations; $i++) {
      $sum += $sign * (4 / $denom);
      yield $sum;

      $sign *= -1;
      $denom += 2;
    }
  }

  // Iterate over the generator 40 times and print the results.
  foreach (calcpi(40) as $value) {
      echo "$value<br/>";
  }

?>

As this example illustrates, we can generate values as many times as needed. Values are not stored in memory. We could iterate over the generator 1 or 1,000,000 times. In our example we put in a limitation which tells the generator that we are going to expect 40 values but in theory we could also have this going on forever until some condition is met. All the variables in the generator are remembered between calls which is nice. Notice that we don’t have to create all the functionality of an iterator class and we have simplified everything down into roughly 9 to 10 lines of code.

We could have created this functionality using a loop to call the function but perhaps we didn’t know how many times we needed to call it because calcPI() was taking into account other values unknown to the caller. Maybe it is reading the system time and while the time was before November 13th 2015, it was to keep generating values. Another example would be a game of Tetris where perhaps we are generating shapes and we don’t know how many shapes we need to generate because it is based on how long the user is playing for. Either way, generators are mainly for convenience, not a radically new design approach.

In part 2 we will be talking about the “finally” keyword along with the simplified password hashing API. We will feature an example code for creating a user and then logging in with that user all through the use of the password API. So stay tuned!

Don’t forget to join The Coders Lexicon circle on Google+ or follow us on Twitter! We often comment on other materials and follow some great developers. Check us out and thanks for reading! 🙂

If you haven’t already, visit our other parts of this series…

About The Author

Martyr2 is the founder of the Coders Lexicon and author of the new ebooks "The Programmers Idea Book" and "Diagnosing the Problem" . He has been a programmer for over 20 years. He works for a hot application development company in Vancouver Canada which service some of the biggest tech companies in the world. He has won numerous awards for his mentoring in software development and contributes regularly to several communities around the web. He is an expert in numerous languages including .NET, PHP, C/C++, Java and more.