https://cdn.rapidweb.biz/wp-content/uploads/2017/04/PHP-logo.svg_-1024x553-1024x553.png

Rapid Web’s Open Source Contributions 2016 & 2017

At the beginning of last year, I posted about our open source contributions from 2015. Most of these projects focused on frontend web development. This time around, the majority of our new open sourced projects are backend code and libraries. They also include a small selection of ‘Simple’ libraries, designed to wrap around complex functionality and abstract it.

Here’s a summary of our main open source projects and contributions from 2016 & early 2017.

SimpleStripe

SimpleStripe is a PHP library that provides developers with a way to very quickly implement a method of charging your customers using Stripe payments. It is handy for adding Stripe as an alternative payment method on an existing site, or adding basic ecommerce functionality to a legacy codebase.

You can read more about SimpleStripe, including installation and usage instructions, in another blog post I wrote, titled SimpleStripe Payments Integration.

SimpleMailChimp

The SimpleMailChimp library is a wrapper around the MailChimp API. It provides really simple methods to integrate the basics of mailing list functionality, such as subscribing, unsubscribing and checking if an email address is present on a list.

$simpleMailChimp->subscribe('LIST_ID_GOES_HERE', 'example@example.com');
$simpleMailChimp->unsubscribe('LIST_ID_GOES_HERE', 'example@example.com');
$simpleMailChimp->isSubscribedToList('LIST_ID_GOES_HERE', 'example@example.com');

Read more about this at the SimpleMailChimp GitHub repository.

PHP Simple Google Maps API

This library is in early development. It currently provides developers with an easy way to convert a postal address or postcode into GPS coordinates (latitude and longitude). This is known as geocoding. It also features the ability to calculate the distance between two sets of GPS coordinates, and return the values as either miles or kilometres.

$addressline = "10 Downing St, Westminster, London SW1A UK";
$homeCoords = $simpleGoogleMaps->getByAddress($addressline);
$latitude = $homeCoords->lat;
$longitude = $homeCoords->long;
$toCoords = $simpleGoogleMaps->getByAddress("ST163DP, UK");
$milesBetween = $homeCoords->distanceTo($toCoords);
$kilometresBetween = $homeCoords->distanceTo($toCoords,"kilometres");

Detailed usage and installation instructions are available at the PHP Simple Google Maps API GitHub repository.

PHP Postcodes

Our PHP Postcodes library provides handy functionality for dealing with UK postcodes. This includes postcode validation, postcode generation (useful for automated testing) and address lookup by postcode. The address lookup by postcode functionality connects to the Ideal Postcodes service. Depending on your usage and situation, this service may be chargeable.

The PHP postcodes is easy to use and can be install via Composer, like most of our PHP libraries.

$addresses = $idealPostcodes->getAddressesByPostcode('ST163DP');
$validated = \RapidWeb\Postcodes\Utils\Validator::validatePostcode('ST163DP');
$postcode = \RapidWeb\Postcodes\Utils\Generator::generatePostcode();

Take a look at PHP Postcodes on GitHub page for more information.

PHP Bucket Testing

Bucket testing is another way of saying A/B testing. Our PHP Bucket Testing library is a tiny system to create weighted server-side redirects in order to test multiple possible destination pages. It does not handle logging of conversions or tracking, which can be best handled by a dedicated service, such as HotJar.

Usage of the PHP Bucket Testing library is simple. You just define your URLs to redirect to, and the chance (‘weight’) each one will be selected for the redirection.

// Create a new bucket manager
$bucketManager = new BucketManager;

// Add buckets, with URLs and optional weights
$bucketManager->add(new Bucket('https://google.co.uk/'))->withWeight(25);
$bucketManager->add(new Bucket('https://php.net/'))->withWeight(75);

// Redirect to a randomly selected URL
$bucketManager->redirect();

For more detailed information, please see the PHP Bucket Testing library GitHub page.

PHP UK Bank Holidays

When working with businesses in the UK that have specific opening and closing hours, we’ve found it useful to be able to programmatically know when bank holidays are. This lead us to create the PHP UK Bank Holidays library.

This library downloads and caches official information provided by the UK government regarding bank holiday dates in England, Scotland, Wales and Northern Ireland. You can use this library to check if there are bank holidays on any specific date or month.

$januaryHolidays = UkBankHolidayFactory::getByMonth(2017, 01);
$newYearsHolidays = UkBankHolidayFactory::getByDate(2017, 01, 2);

It returns an easily used array of objects containing all the details of all holidays that occur in the stated period.

array(1) {
  [0]=>
  object(RapidWeb\UkBankHolidays\Objects\UkBankHoliday)#46 (4) {
    ["title"]=>
    string(16) "New Year’s Day"
    ["date"]=>
    string(10) "2017-01-02"
    ["notes"]=>
    string(14) "Substitute day"
  }
}

The PHP UK Bank Holidays GitHub page contains installation instructions for this library and additional documentation.

RW File Cache

Although this project was started in 2015, it has been continually improved over this year with several new releases.

RW File Cache is a package that provides a file based caching system, with some advanced features. It provides a syntax similar to the PHP memcache extension.

Developers are able to specify where to store cache files, the file extension to use and whether to use gzip compression. It is also possible to specify an unix load upper threshold. If your server is busy and exceeds this upper threshold, RW File Cache will automatically serve old (stale) files regardless of their specified expiry time. This means potentially expensive code will not be run if your server is overloaded.

Examples of setting and getting cache items from the file cache are as follows.

$cache->set('nursery_rhyme',"Mary had a little lamb", strtotime('+ 1 day'));
$var = $cache->get('nursery_rhyme');

For more detailed examples and documentation, see RW File Cache on GitHub.

Improved Polymorphic Eloquent Builder

In a recent Laravel-based project, we were tasked with creating a system that made use of a polymorphic database relationship. In Laravel, attempting to query polymorphic relationships using the whereHas Eloquent model method will fail. This is caused by Eloquent being unable to determine the correct related model to retrieve. In these cases, you may receive an error similar to the following.

QueryException in Connection.php line 662:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'column_name' in 'where clause'

We therefore created an ‘Improved Polymorphic Eloquent Builder’ package that overrides default Laravel functionality in order to work around this issue. Unfortunately, a complete fix for this issue is impossible due to the nature of polymorphic relationships. However, this package provides limited use of the whereHas method to query these types of relationships.

For more information about this package, including how to setup an Eloquent model to use the builder, see the Improved Polymorphic Eloquent Builder on GitHub.

No Post Data Laravel Middleware

In some situations, when posting data from a form, the web server may lose the associated post data. This commonly occurs if a file exceeds the maximum file upload size as defined in the web server’s configuration. This is usually noticed during an attempt to upload a very large image or video file to a site.

In Laravel, this situation is not handled specifically and results in a confusing TokenMismatchException in VerifyCsrfToken error.

The No Post Data Laravel Middleware package deals specifically with scenarios in which a post request is made but contains no post data. Under typical web application use, this should not occur. If a post request occurs, but no post data is present, the middleware will redirect back to the previous page with an error. Both the error messages and this behaviour can be entirely customised if needed.

Head to No Post Data Laravel Middleware on GitHub if you want more information about this issue and instructions on how to setup this package in your Laravel project.

Amazon MWS Config Generator

CPI Group have written and open sourced an Amazon Marketplace Web Services library. It acts as a wrapper for the Amazon MWS API. The library allows for uploading of products and their changes to Amazon, along with inventory changes and most other MWS features.

In order to dynamically use this in multiple projects, we created a small package that allows generation of the configuration files required by this library. Developers provide the necessary configuration variables in an object orientated manner and then this package will output a correctly formatted configuration file with a unique name.

Example usage and basic documentation can be found at the Amazon MWS Config Generator GitHub repository.