Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

SitePoint PHP Blog:
How to Read Big Files with PHP (Without Killing Your Server)
Nov 21, 2017 @ 13:19:27

On the SitePoint PHP blog, there's a tutorial posted showing you how to deal with large files without "killing your server". In this case, it's not about the upload process but about the handling of large files on the server side.

It’s not often that we, as PHP developers, need to worry about memory management. The PHP engine does a stellar job of cleaning up after us, and the web server model of short-lived execution contexts means even the sloppiest code has no long-lasting effects.

There are rare times when we may need to step outside of this comfortable boundary — like when we’re trying to run Composer for a large project on the smallest VPS we can create, or when we need to read large files on an equally small server. It’s the latter problem we’ll look at in this tutorial.

They start off by describing how they plan to measure the success of the improved file handling, mostly around the memory usage required to work with the file. It then gets into some of the options available including:

  • reading files line by line
  • piping between files
  • using filters

The last option, the filters, seems to be the best one. He uses this one and customizes the handling with different configurations and custom protocols. All related code is included in the post and is avaialble on GitHub.

tagged: read big file memory consumption filter stream tutorial

Link: https://www.sitepoint.com/performant-reading-big-files-php/

Zend Framework:
Convert objects to arrays and back with zend-hydrator
Jun 21, 2017 @ 11:32:01

The Zend Framework blog has posted another in their series of component spotlights, focusing in on a single component of the framework and its use. In this latest article they cover the zend-hydrator component, useful for converting objects to arrays and back.

APIs are all the rage these days, and a tremendous number of them are being written in PHP. When APIs were first gaining popularity, this seemed like a match made in heaven: query the database, pass the results to json_encode(), and voilà! API payload! In reverse, it's json_decode(), pass the data to the database, and done!

Modern day professional PHP, however, is skewing towards usage of value objects and entities, but we're still creating APIs. [...] Zend Framework's answer to that question is zend-hydrator. Hydrators can extract an associative array of data from an object, and hydrate an object from an associative array of data.

They start with the command to get the zend-hydrator package installed (and a dependency they'll need for their examples, zend-filter). A code example is included that shows how to convert a "book" object to an array using the ReflectionHydrator. Next is an example of switching it back, changing the array of data back into a book object. Next comes the integration with zend-filter, showing how to filter values out of objects/arrays you might not want in the end result by adding the filter to the hydrator. Also included are examples of modifying data (strategies), filtering on property names, delegation of the translation based on object type and a few other features included in the component that could be helpful.

tagged: zendframework component zendhydrator tutorial introduction filter translate

Link: https://framework.zend.com/blog/2017-06-21-zend-hydrator.html

Rob Allen:
Simple way to add a filter to Zend-InputFilter
Jun 21, 2017 @ 09:16:29

Rob Allen has a quick new post to his site sharing a simple way to add a filter to the Zend-InputFilter component when it's in use on your site.

Using Zend-InputFilter is remarkably easy to use. [...] How do you add your filter to it though?

He starts with an example of putting the component to use in requiring and filtering the value in "my_field" for the data provided. He then shows how to add his "simple filter that does absolutely nothing", the MyFilter, to the current set. He also shows the creation of a "filter factory" class that registers the custom filter into the chain with an alias of "MyFIlter". You can then use it just like you would any other filter and define it in your rules specification.

tagged: zendframework zendinputfilter component custom filter tutorial factory

Link: https://akrabat.com/simple-way-to-add-a-filter-to-zend-inputfilter/

Zend Framework Blog:
Validate data using zend-inputfilter
Jun 16, 2017 @ 09:22:37

Matthew Weier O'Phinney is back on the Zend Framework blog today with a spotlight on another component of the Zend Framework. This time he features zend-inputfilter, a useful component for filtering the data coming into your application from your users.

In our previous two posts, we covered zend-filter and zend-validator. With these two components, you now have the tools necessary to ensure any given user input is valid, fulfilling the first half of the "filter input, escape output" mantra.

[...] To solve [the single shot validation] problem, Zend Framework provides zend-inputfilter. An input filter aggregates one or more inputs, any one of which may also be another input filter, allowing you to validate complex, multi-set, and nested set values.

As in the other tutorials in the series, Matthew walks you through the installation of the component via Composer and briefly describes how it operates. He then includes a code example of creating a new InputFilter instance, making inputs, attaching validators to them and then ensuring everything validates in the chain with an isValid call. He then covers input specifications - configurations based on array values - to define validators on the input elements. He ends the post looking at input filters, how to manage them and defining them by specification. He also mentions a few other pieces fo functionality the component includes but he didn't cover here.

tagged: zendinputfilter component zendframework series input filter chain

Link: https://framework.zend.com/blog/2017-06-15-zend-inputfilter.html

Amazon Web Services:
PHP application logging with Amazon CloudWatch Logs and Monolog
Apr 24, 2017 @ 09:46:47

On the Amazon Web Services blog there's a new post showing you how to use the Monolog logging library and a custom AWS extension to ship your logs to Amazon CloudWatch quickly and easily.

Logging and information debugging can be approached from a multitude of different angles. Whether you use an application framework or coding from scratch it’s always comforting to have familiar components and tools across different projects. In our examples today, I am going to enable Amazon CloudWatch Logs logging with a PHP application. To accomplish this, I wanted to use an existing solution that is both already popular and well used, and that is standards compliant. For these reasons, we are going to use the open source log library, PHP Monolog (https://github.com/Seldaek/monolog).

They start by introducing the Monolog library for those not familiar with it and how it relates to the PSR-3 standard. The ultimate goal with their implementation is to allow for the logs to be shipped to CloudWatch and implement some alerting around them. The tutorial then kicks in and they show you how to use Composer to install Monolog and an add-on to interface with CloudWatch. Code is provided to set up the initial logger and how to have it to log messages to different places. They then move over to CloudWatch and define a filter for the JSON data to find successful logins to your application. They also show how to use this same functionality in a Laravel application, contained in a test route.

tagged: aws amazon logging cloudwatch monolog tutorial install usage filter

Link: https://aws.amazon.com/blogs/developer/php-application-logging-with-amazon-cloudwatch-logs-and-monolog/

Fabian Schmengler:
Collection Pipelines in PHP
Dec 28, 2016 @ 12:24:24

In a new post to his site Fabian Schmengler has written up an introduction to collection pipelines and how it could be applied to a Magento-based environment.

If you read the book “Refactoring to Collections” or saw screencasts and talks by Adam Wathan about collection pipelines, but do not work with Laravel, you might have asked yourself how to apply these techniques to other PHP applications, for example Magento.

[...] This is very similar to Unix pipes, where the individual commands are the operations, and the lines passed through input and output stream, the collection.

He starts by illustrating the idea in Bash and Ruby, showing the three main types of collection operations: map, filter and reduce. He talks about the advantages these methods have over traditional looping and what kind of value they can provide in both Laravel and plain old PHP. He illustrates the PHP-only versions using the array_filter, array_map and array_reduce functions and some thoughts on when it's good to use them over normal looping (and when it's not). He then gets into the Magento-specific handling and making use of a package to handle collections: Knapsack. He shows how to use the library to work with collections and, as another option, a "home-grown" version that lives in a single class. The post wraps up with the Magento integration of this functionality, a brief mention of functional programming and "the hard part" of issues with debugging.

tagged: collection pipeline package knapsack magento integration tutorial introduction map reduce filter

Link: https://www.schmengler-se.de/en/2016/12/collection-pipelines-in-magento/

Sherif Ramadan:
Bloom Filters in PHP
Jun 22, 2016 @ 10:56:26

On his site Sherif Ramadan has posted an interesting tutorial covering implementing bloom filters in PHP. Bloom filters are data structures that make it easier to determine if something is a member of a set.

Let's imagine you have built a music app like Spotify. You've finally grown this thing to sizeable amount of users and you have a decent number of titles in your content library. Let's also say this app has social elements to it so your users can connect with their facebook friends or twitter followers. Now, let's say each time your users play a song in your app you want to ask the question Which of this user's friends have NOT listened to this song yet? The intention being that you may recommend that song to them if they haven't listened to it.

One solution to this problem is to use a data structure known as a bloom filter. A bloom filter is basically a very space-efficient hash set with probabilistic tendency. If you aren't familiar with a hash set or sets in general, let's do a quick review of what they mean.

He goes on to explain what a bloom filter is and how it differs from normal sets, hash sets and hash maps. He then introduces some of the basic concepts involved in creating and using bloom filters. To help make things clearer, he provides a "contrived example" using lightbulbs and the probably that they've been turned on. From there he starts to get into something more practical, something more in the world of PHP. He includes a basic Bloomfilter class example and some of the results (performance) of using it over something like in_array (especially for large data sets).

tagged: bloom filter example tutorial introduction probability set

Link: http://phpden.info/Bloom-filters-in-PHP

Dotdev.co:
Writing advanced Eloquent search query filters
Jun 15, 2016 @ 11:10:04

In a new post from the Dotdev.co site there's a tutorial from Amo Chohan helping you write advanced search query filters for Eloquent in your Laravel application.

I recently needed to implement a search feature in an events management project I was building. What begun as a few simple options (searching by name, e-mail etc), turned into a pretty large set of parameters.

Today, I’ll go over the process I went through and how I built a flexible and scalable search system. For those of you who are eager to see the final code, head over to the Git repository to see the code.

He starts off by outlining what he'll be creating and where the need comes from for this more advanced filtering. He uses a company-wide calendar example with events and meetings/clients shown for all users. He defines the filters he knows he'll want to search by and the models relating to the data needed for those queries. He then spends the rest of the post going through the code needed to implement the filtering, starting with a rough (but working) version and refactoring from there. He moves away from the procedural method of applying filters to a query object directly and over to "applying" them more dynamically using a set of filter instances via a Decorator design pattern approach.

tagged: advanced eloquent filter search decorator apply refactor tutorial

Link: https://dotdev.co/writing-advanced-eloquent-search-query-filters-de8b6c2598db#.16sfoe3a8

Rob Allen:
Filtering the PSR-7 body in middleware
May 16, 2016 @ 09:25:30

Rob Allen has a post to his site showing how you can filter the body content of your response in a PSR-7 compatible system via some simple middleware.

Sometimes, there's a requirement to alter the data in the Response's body after it has been created by your controller action. For example, we may want to ensure that our brand name is consistently capitalised. One way to do this is to create middleware that [uses str_ireplace to replace a string]. That's great, but what happens if the new string is shorter than the old one? For instance, suppose I want to replace all uses of "nineteen feet" with "19FT".

In his example, replacing that part of the content would result in an odd string because of how they'd be replaced in the stream. He shows how to use the in-memory handling of PHP's fopen to create a new content instance to push back into the response and back out to the waiting application.

tagged: psr7 middleware filter content strireplace stream fopen tutorial

Link: https://akrabat.com/filtering-the-psr-7-body-in-middleware/

Edd Mann:
Mapping, Filtering and Reducing in PHP
Mar 03, 2016 @ 09:28:27

Edd Mann has a post to his site talking about the use of things like "map" and "reduce" in his own development and how to use it in PHP to help reduce data sets and filter them based on certain criteria.

Over the past couple of years I have transitioned from boilerplate-heavy, imperative code, to begin using the more intuitive map, filter and reduce higher-order functions. In this article I hope to highlight the transformation that occurs, along with simplification, when moving away from the imperative and onto the declarative. We shall be performing a simple process which transforms a collection of user entries into a filtered collection of their names. Although trivial in nature, it is a great place to highlight the power of the paradigm shift.

He starts with a simple array of data: a set of users with their respective IDs and names. He shows a typical approach, using a method that loops through the data to find only the "name" values. He then shows an alternative that makes use of PHP's own array_filter and array_reduce functions to perform the same operation with just a bit more internal handling.

tagged: filter reduce array arrayfilter arrayreduce example simple

Link: http://eddmann.com/posts/mapping-filtering-and-reducing-in-php/