25 Jun 2017

feedPlanet PHP

Profiling Spark Applications: The Easy Way

25 Jun 2017 7:14am GMT

23 Jun 2017

feedPlanet PHP

Hello, Laravel? Communicating with PHP through SMS!

In this article, we will modify our Laravel-powered phone-capable weather forecast app so that it is accessible via SMS (text message) in addition to the voice telephone system. It is recommended you read the previous post if you haven't done so yet - it's a 10 minute read for an excellent outcome.

Note: If you're confused by the development environment we're using, it's Homestead Improved and you can learn more about it here, or go in detail by buying our book about PHP environments.

Vector icon of phone with weather icon overlaid

Adding Routes

To allow for SMS communication, we need some more routes. Open up the routes/web.php file and append the following code to it:

Route::group(['prefix' => 'sms', 'middleware' => 'twilio'], function () {
    Route::post('weather', 'SmsController@showWeather')->name('weather');
});

The prefix for the route is sms, so that routes will have a path like /sms/weather, as the one in the example. This is the only route we need for SMS, as Twilio will call the same route over and over again. Twilio will access it via HTTP POST. We could also do this without the prefix, but it's more flexible this way if we decide to add more functionality to the SMS side later.

Service Layer

Next, we'll modify the service we wrote previously. Open up the app/Services/WeatherService.php file and remove the current getWeather method, then replace it with the one below:

    public function getWeather($zip, $dayName, $forSms = false)
    {

        $point = $this->getPoint($zip);
        $tz = $this->getTimeZone($point);
        $forecast = $this->retrieveNwsData($zip);
        $ts = $this->getTimestamp($dayName, $zip);

        $tzObj = new \DateTimeZone($tz->timezoneId);

        $tsObj = new \DateTime(null, $tzObj);
        $tsObj->setTimestamp($ts);

        foreach ($forecast->properties->periods as $k => $period) {
            $startTs = strtotime($period->startTime);
            $endTs = strtotime($period->endTime);

            if ($ts > $startTs and $ts < $endTs) {
                $day = $period;
                break;
            }
        }

        $weather = $day->name;
        $weather .= ' the ' . $tsObj->format('jS') . ': ';

        $response = new Twiml();

        if ($forSms) {
            $remainingChars = 140 - strlen($weather);

            if (strlen($day->detailedForecast) > $remainingChars) {
                $weather .= $day->shortForecast;
                $weather .= '. High of ' . $day->temperature . '. ';
                $weather .= $day->windDirection;
                $weather .= ' winds of ' . $day->windSpeed;
            } else {
                $weather .= $day->detailedForecast;
            }

            $response->message($weather);
        } else {
            $weather .= $day->detailedForecast;

            $gather = $response->gather(
                [
                    'numDigits' => 1,
                    'action' => route('day-weather', [], false)
                ]
            );

            $menuText = ' ';
            $menuText .= "Press 1 for Sunday, 2 for Monday, 3 for Tuesday, ";
            $menuText .= "4 for Wednesday, 5 for Thursday, 6 for Friday, ";
            $menuText .= "7 for Saturday. Press 8 for the credits. ";
            $menuText .= "Press 9 to enter in a new zipcode. ";
            $menuText .= "Press 0 to hang up.";

            $gather->say($weather . $menuText);
        }

        return $response;
    }

This function is very similar to the old one. The only difference is that it takes into consideration that the weather request might be coming form a telephone device via SMS, so it makes sure that the weather forecast isn't too long and tries to limit it to less than 140 characters. The response for SMS is still TwiML, just formatted for SMS.

Continue reading %Hello, Laravel? Communicating with PHP through SMS!%

23 Jun 2017 4:00pm GMT

22 Jun 2017

feedPlanet PHP

PHP 7.2.0 Alpha 2 Released

The PHP development team announces the immediate availability of PHP 7.2.0 Alpha 2. This release contains fixes and improvements relative to Alpha 1. All users of PHP are encouraged to test this version carefully, and report any bugs and incompatibilities in the bug tracking system.THIS IS A DEVELOPMENT PREVIEW - DO NOT USE IT IN PRODUCTION!For information on new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive.For source downloads of PHP 7.2.0 Alpha 2 please visit the download page, Windows sources and binaries can be found on windows.php.net/qa/.The third and final alpha will be released on the 6th of July. You can also read the full list of planned releases on our wiki.Thank you for helping us make PHP better.

22 Jun 2017 12:00am GMT

21 Jun 2017

feedPlanet PHP

Interview with Heather White

cattyheather Audio Show Notes Fredrick Web Tech Coder Cruise

The post Interview with Heather White appeared first on Voices of the ElePHPant.

21 Jun 2017 5:29pm GMT

What Is Snapshot Testing, and Is It Viable in PHP?

A vector image of a polaroid glued to a transparent background

Ah-ha moments are beautiful and rare in programming. Every so often, we're fortunate enough to discover some trick or facet of a system that forever changes how we think of it.

For me, that's what snapshot testing is.

You probably write a lot of PHP code, but today I want to talk about something I learned in JavaScript. We'll learn about what snapshot testing is and then see how it can help us write better PHP applications.

Building Interfaces

Let's talk about React. Not the kick-ass async PHP project, but the kick-ass JavaScript project. It's an interface-generation tool in which we define what our interface markup should look like as discrete parts:

function Tweet(props) {
  return (
    <div className="tweet">
      <img src={props.user.avatar} />
      <div className="text">
        <div className="handle">{props.user.handle}</div>
        <div className="content">{props.content}</div>
      </div>
    </div>
  )
}

function Tweets(props) {
  return (
    <div className="tweets">
      {props.tweets.map((tweet, i) => {
        return (
          <Tweet {...tweet} key={i} />
        )
      })}
    </div>
  )
}

This doesn't look like vanilla Javascript, but rather an unholy mix of html and Javascript. It's possible to create React components using regular Javascript syntax:

function Tweet(props) {
  return React.createElement(
    "div",
    { className: "tweet" },
    React.createElement("img", { src: props.user.avatar }),
    React.createElement(
      "div",
      { className: "text" },
      React.createElement(
        "div",
        { className: "handle" },
        props.user.handle
      ),
      React.createElement(
        "div",
        { className: "content" },
        props.content
      )
    )
  );
}

To make this code, I pasted the Tweet function (above) into the Babel REPL. That's what all React code is reduced to (minus the occasional optimization) before being executed by a browser.

Before I talk about why this is cool, I want to address a couple of issues...

"Why Are You Mixing html and Javascript?!"

We've spent a lot of time teaching and learning that markup shouldn't be mixed with logic. It's usually couched in the phrase "Separation of Concerns". Thing is, splitting html and the Javascript which makes and manipulates that html is largely without value.

Splitting that markup and Javascript isn't so much separation of concerns as it is separation of technologies. Pete Hunt talks about this in more depth in this video.

"This Syntax Is Very Strange"

That may be, but it is entirely possible to reproduce in PHP and works out the box in Hack:

class :custom:Tweet extends :x:element {
  attribute User user;
  attribute string content;

  protected function render() {
    return (
      <div class="tweet">
        <img src={$this->:user->avatar} />
        <div class="text">
          <div class="handle">{$this->:user->handle}</div>
          <div class="content">{$this->:content}</div>
        </div>
      </div>
    );
  }
}

I don't want to in detail about this wild syntax except to say that this syntax is already possible. Unfortunately, it appears the official XHP module only supports HHVM and old versions of PHP...

Testing Interfaces

There are many testing approaches - some more effective than others. An effective way to test interface code is by faking (or making) a web request and inspecting the output for the presence and content of specific elements.

Perhaps you've heard of things like Selenium and Behat? I don't want to dwell too much on them. Let's just say that Selenium is a tool we can use to pretend to be a browser, and Behat is a business-friendly language for scripting such pretense.

Unfortunately, a lot of browser-based testing can be brittle. It's tied to the exact struct

Truncated by Planet PHP, read more at the original (another 2019 bytes)

21 Jun 2017 4:00pm GMT

Simple way to add a filter to Zend-InputFilter

Using Zend-InputFilter is remarkably easy to use: [crayon-594b3a6d8e45f214434617/] How do you add your filter to it though? This is the world's most simple filter that does absolutely nothing: We'll call it MyFilter and store it in App\Filter\MyFilter.php: [crayon-594b3a6d8e46e945342138/] Now you have a couple of choices: Extend Zend\InputFilter\Factory I needed to add my own filter in […]

21 Jun 2017 10:02am GMT

20 Jun 2017

feedPlanet PHP

How to make Sculpin skip certain sources

20 Jun 2017 7:30pm GMT

19 Jun 2017

feedPlanet PHP

Making a Docker image ready for use with Swarm Secrets

19 Jun 2017 7:30pm GMT

Hello, Laravel? Communicating with PHP through Phone Calls!

Vector icon of smartphone with weather icon overlay

Twilio is a SaaS application which enables developers to build telephone applications using web technologies. In this two-part series, we will leverage Twilio to build a weather forecast app that is accessed using the telephone system. The backend will be written with the Laravel framework (an exploratory video course is available for purchase here, or in the form of written tutorials here).

In this part, we will create a simple program that will allow a user to call a phone number that we buy from Twilio, enter a zipcode, and receive the current weather forecast. The user can also get the weather for any day of the week via the voice menu prompts. In the second part of this series, we will leverage what was built in this article to allow the user to interact with the app via SMS (text message).

Prerequisites

Development Environment

This article assumes Homestead Improved is installed. It is not necessary to use it, but the commands might differ slightly if you use a different environment. If you are not familiar with Homestead and want to produce similar results as this article aims to produce, please visit this SitePoint article that shows how to set up Homestead, and if you need a crash course in Vagrant, please see this post. Additionally, if this whets your appetite and you feel like exploring PHP development environments in depth, we have a book about that available for purchase.

Dependencies

We will create a new Laravel project and then add the Twilio PHP SDK and Guzzle HTTP client library to the project:

cd ~/Code
composer create-project --prefer-dist laravel/laravel Laravel 5.4.*
cd Laravel
composer require "twilio/sdk:^5.7"
composer require "guzzlehttp/guzzle:~6.0"

Development

Let's go through all the steps, one by one.

Routes

Open up the routes/web.php file and add the following ones:

Route::group(['prefix' => 'voice', 'middleware' => 'twilio'], function () {
    Route::post('enterZipcode', 'VoiceController@showEnterZipcode')->name('enter-zip');

    Route::post('zipcodeWeather', 'VoiceController@showZipcodeWeather')->name('zip-weather');

    Route::post('dayWeather', 'VoiceController@showDayWeather')->name('day-weather');

    Route::post('credits', 'VoiceController@showCredits')->name('credits');
});

In this app, all requests will be under the /voice path. When Twilio first connects to the app, it will go to /voice/enterZipcode via HTTP POST. Depending on what happens in the telephone call, Twilio will make requests to other endpoints. This includes /voice/zipcodeWeather for providing today's forecast, /voice/dayWeather, for providing a particular day's forecast, and /voice/credits for providing information on where the data came from.

Service Layer

We are going to add a service class. This class will hold a lot of the business logic that will be shared between the voice telephone app and the SMS app.

Create a new sub-folder called Services inside the app folder. Then, create a file called WeatherService.php and put the following content into it:

<?php

namespace App\Services;

use Illuminate\Support\Facades\Cache;
use Twilio\Twiml;

class WeatherService
{
}

This is a large file in the project, so we will build it piece by piece. Put the following pieces of code in this section inside our new service class:

    public $daysOfWeek = [
        'Today',
        'Sunday',
        'Monday',
        'Tuesday',
        'Wednesday',
        'Thursday',
        'Friday',
        'Saturday'
    ];

We will use this array to map a day of the week to a number; Sunday = 1, Monday = 2, etc.

    public function getWeather($zip, $dayName)
    {

Truncated by Planet PHP, read more at the original (another 6325 bytes)

19 Jun 2017 4:00pm GMT

16 Jun 2017

feedPlanet PHP

Being a Full Stack Developer

Jack of all trades

A full stack developer who can get from a prototype to full MVP (minimum viable product) is often considered a jack of all trades, master of none, and with good reason. To define the modern full stack developer, we first need to focus on what the full stack developer used to be.

Full Stack Developers Then

Long ago, circa 2000 (in Internet-time, 17 years is a very long time ago), a full stack developer was someone who could:

Note that we're talking about PHP here - a full stack Flash or Coldfusion developer had a different (but only slightly different) workflow.

Those were simple times, life was good. One-man agencies were a dime a dozen, and people still had time to spend with their family after work.

What about now?

What Does a Full Stack Developer Need to Know Now?

These days, we have horrors like these happening - how did it come to this?

App developer doesn't see his kids due to schedule

To succeed in a now-saturated market, we developers - who are often perfectionists - hesitate to delegate and often live by the "if you want something done right" motto. This forces us into a corner where we have to learn everything, so that being a full stack developer often ends up encompassing the following.

Server Admin / Devops

A developer must know how to do basic server management. This includes but is not limited to:

via GIPHY

Apart from these basics, a developer should know how to create good, healthy, isolated development environments, in either Docker or virtual machines like with Vagrant. If all of the above is something you're unfamiliar with, we have an excellent book about it for sale here.

The developer should also be intimately familiar with version control systems in order to be able to reliably produce backups and shareable, collaborative collections of code, tracked for changes across time. No modern developer workflow is complete without version control these days. We have a fantastic video course about this for purchase here.

Cloud

Apart from actual managed or virtualized servers, a developer might need to know about the cloud - hosting on platforms like Heroku, Google Cloud, Azure, AWS, and others.

via GIPHY

There's a fair bit to be said about platforms and tools that are more hype than immediately useful, but being familiar with the services everyone is talking about can come in handy in the long run - a client could demand a switch of providers any day now, and it pays to be ready. Luckily, we have the

Truncated by Planet PHP, read more at the original (another 2200 bytes)

16 Jun 2017 3:00pm GMT