SitePoint PHPThe Balance between Visual and Technical Debt in PHP (29.5.2017, 16:00 UTC)

Laracasts recently published a very interesting non-Laravel video about something called visual debt. It's only 3 minutes long, so please, take the time to watch it before reading further.

A still screen from the referenced video

Done? Okay, spoilers below.

In the video, Jeff starts out with with a bit of verbose event-based code with some listeners, fire methods, an interface on which to base the various classes, and quite a few type and return hints all over the place.

As he scrolls through the code, he claims it's full of visual debt. Jeff then goes on to explain that while PHP does offer type and return hints, they aren't necessary, and promptly removes them from all method signatures to reduce the amount of code. "We were doing fine for a really long time without them", he argues.

He then reaches for interfaces and removes those, too. He argues that people reach for them too often, too soon, and add unnecessary weight to their code.

In what seems like a final cut, he removes the "final" keyword from a class arguing that it's silly to protect a developer from themselves, but then unexpectedly, he also cuts out even the public keyword in front of the remaining methods, leaving them at the language default (which, incidentally, is an implied public).

The end result? About 25% less code in this simple example. But is the debt gone?

Continue reading %The Balance between Visual and Technical Debt in PHP%

SitePoint PHPDay Camp 4 Developers: PHP Application Security (27.5.2017, 16:00 UTC)

Application security is on everybody’s mind these days. Every day we hear of another site hacked or another data breach. Does your team do everything it can to keep your site secure and your data safe?

Day Camp 4 Developers is a semi-regular online meetup of developers who want to teach people things that don't appear in the regular curriculum of your average conference. It's about exploring PHP in specific ways that don't have to conform to a generalist lineup to please as many people as possible, but instead narrow the focus to a specific area of development or soft skills around it.

Day Camp 4 Developers logo

Cal Evans, the godfather of PHP, draws in a very interesting crowd every single time and makes sure the topics are contextually linked, but unique and interesting across the spectrum.

Previous iterations of the event dealt with everything from telecommuting and speaking in front of an audience to performance, in-depth debugging, and building good APIs.

This time, DC4D's focus is application security in the PHP world, featuring such acclaimed speakers as Ben Ramsey (speaking about OAuth2), Adam Englander (explaining cryptography), Scott Arciszewski (on Libsodium), Sammy Powers (talking about randomness in PHP) and finally, Eric Mann (who'll be teaching us about the proper way to store passwords and credentials in code).

Continue reading %Day Camp 4 Developers: PHP Application Security%

SitePoint PHPHow to Build a Twitter Follower-Farmer Detection App with RestDB (26.5.2017, 20:30 UTC)

Twitter birds

This article was sponsored by RestDB. Thank you for supporting the partners who make SitePoint possible.

Are you active on Twitter? If so, do you often wonder why some accounts seem to follow you only to unfollow you moments (or days) later? It's probably not something you said - they're just follower farming.

Follower farming is a known social media hack taking advantage of people who "#followback" as soon as someone follows them. The big brands, celebs, and wannabe celebs take advantage of this, as it keeps their followers count high but following count low, in turn making them look popular.

Outline of twitter logo

In this post, we'll build an app which lets you log in via Twitter, grabs your followers, and compares the last fetched follower list with a refreshed list in order to identify the new unfollowers and calculate the duration of their follow, potentially auto-identifying the farmers.


As usual, we'll be using Homestead Improved for a high quality local environment setup. Feel free to use your own setup instead if you've got one you feel comfortable in.

git clone hi_followfarmers
cd hi_followfarmers
vagrant up; vagrant ssh

Once the VM has been provisioned and we find ourselves inside it, let's bootstrap a Laravel app.

composer create-project --prefer-dist laravel/laravel Code/Project
cd Code/Project

Logging in with Twitter

To make logging in with Twitter possible, we'll use the Socialite package.

composer require laravel/socialite

As per instructions, we should also register it in config/app.php:

'providers' => [
    // Other service providers...


'Socialite' => Laravel\Socialite\Facades\Socialite::class,

Finally, we need to register a new Twitter app at

Registering a new Twitter app

... and add the secret credentials into config/services.php:

    'twitter' => [
        'client_id' => env('TWITTER_CLIENT_ID'),
        'client_secret' => env('TWITTER_CLIENT_SECRET'),
        'redirect' => env('TWITTER_CALLBACK_URL'),

Naturally, we need to add these environment variables into the .env file in the root of the project:


We need to add some Login routes into routes/web.php next:

Route::get('auth/twitter', 'Auth\LoginController@redirectToProvider');
Route::get('auth/twitter/callback', 'Auth\LoginController@handleProviderCallback');

Finally, let's add the methods these routes refer to into the LoginController class inside app/Http/Controllers/Auth:

     * Redirect the user to the GitHub authentication page.
     * @return Response
    public function redirectToProvider()
        return Socialite::driver('twitter')->redirect();

     * Obtain the user information from GitHub.
     * @return Response
    public function handleProviderCallback()
        $user = Socialite::driver('twitter')->user();


The dd($user); is there to easily test if the authentication went well, and sure enough, if you visit /auth/twitter, you should be able to authorize the app and see the basic information about your account on screen:

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

SitePoint PHPWeb App Performance Testing with Siege – Plan, Test, Learn (25.5.2017, 16:00 UTC)

Building a simple web application today isn’t that hard. The web development community is friendly, and there are lots of discussions on Stack Overflow or similar platforms, and various sites with lessons and tutorials.

Almost anyone can build an app locally, deploy it to a server, and proudly show it to your friends. I hope you’ve already done all of this, and your project went viral, so you’re obviously here because you want to learn how to make sure your app is ready for some high traffic.

If we think about a web app as a black box, things are quite simple - the app waits for a request, processes it, and returns the response presentation of a resource (HTML, JSON, XML, etc.). One could think: “Yeah, that’s simple, we should be able to scale our app with ease.” Sadly, the world of web development ain't all sunshine and rainbows, and you’ll encounter a lot of performance issues while your traffic grows! You will learn and improve both your skills and the app over time. In this article, designed to speed this process up, I will cover the basic concepts of testing the app (regression, load, and stress testing) with Siege and some tips and tricks I like to use when I’m testing my own web apps.

Vector image of catapult

The Types of Testing

Let’s say we want to achieve the daily goal of 1 million unique users. How should we prepare for that amount of traffic? How do we make sure nothing will break under normal traffic or peaks? This type of testing is called load testing, since we know exactly how much traffic we want our app to endure - the load. If you want to push your app to its limits and beyond until it breaks, you’re stress testing your app.

In addition to those, are you aware of how code changes you’ve deployed might affect performance? One simple update can degrade or improve the performance of a high traffic web app to a large extent, and you won’t even know what happened or why until the storm is over. To make sure an app is performing the same before and after a change, we’re doing regression testing.

Another great motivation for regression testing is infrastructure change: for whatever reason, you might want to move from provider A to provider B (or switch from Apache to Nginx). You know that your app is usually handling N requests per minute (on average) and what its normal traffic is (a quick look at analytics would do the job). You’re expecting that your app will behave the same (or better) once deployed provider B's server. Are you sure, though? Would you take that risk? You already have all the data you need, don’t guess! Test your new setup before deploying and sleep better!

Before you start randomly hitting your app with virtual requests, you should know that testing is not an easy job, and the numbers you’ll get from Siege or any other testing tool should be used as a reference to analyze relative changes. Running both Siege and the app locally for five minutes and concluding your app can handle a few hundred or thousand requests within a few seconds is not something I’d recommend.

The Steps for Successful Testing

  • Plan

    Think about what you want to test. and what you expect. How much traffic, on which URLs, with what payload? Define parameters up front, don’t just randomly hit your app.

  • Prepare

    Make sure your environments are as isolated as possible - use the same environment for testing, for every test run. A good guide on how to accomplish this can be found in this book about setting up PHP environments.

  • Analyze and Learn

    Learn something from the numbers and make educated decisions. Results should always be evaluated within their context - don’t jump to conclusions. Check everything at least twice.

Getting started with Siege

Siege is an awesome tool for benchmarking and testing web apps. It simulates concurrent users requesting resources at a given URL (or multiple URLs) and lets the user heavily customize the testing parameters. Run siege --help to see all available options; we’ll cover some of them in detail below.

Preparing the test app

With Siege, you can test an app's stability, performance, and improvements between code (or infrastructure) changes. You can also use it to make sure your Wor

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

SitePoint PHPRe-Introducing Symfony Console – CLI PHP for the Uninitiated! (24.5.2017, 16:00 UTC)

"The console component eases the creation of beautiful and testable command line interfaces."

This is how we are welcomed when we visit the Symfony Console component tool page.

As software developers, we often feel the need to resort to command line tools. These kinds of tools are helpful when we need to do a sort of recurring task like migrating data, performing imports, or creating cron jobs.

Vector image of a terminal or console application

The Symfony Console component tool offers provides us with a simple framework to create our own command line tools.

Unlike many components in Symfony, this is a stand alone package and is used by the likes of Laravel's Artisan and many other famous PHP packages.

To read up on alternatives to Symfony Console, see our comparison post: PHP Console Wars!


composer require symfony/console

Essential information about Composer here.

Creating a new command

To create a new command, we need to make sure our file will be executable. In order to do that, let's create a console file in the root of our project. This file will be our command manager.

touch console

Now, let's make sure the file is executable.

chmod 755 console

Then, let's make sure our file has the shebang at the beginning. The shebang is a character sequence (a number sign followed by an exclamation mark) that appears at the beginning of a script. When the shebang is present, exec() will instead run the executable specified after the shebang. In our case, it will run as a PHP script.

After this, let's define our console application. The first iteration of our command manager will look like this:

#!/usr/bin/env php


require_once __DIR__ . '/vendor/autoload.php';

use Symfony\Component\Console\Application;

$app = new Application();


Let's take a closer look at things. First, we are autoloading all our dependencies, then importing the Application package from the Console component. After that, we are creating a new instance of the Application and running it.

Continue reading %Re-Introducing Symfony Console – CLI PHP for the Uninitiated!%

thePHP.ccTesting Keeps Me From Getting Things Done (24.5.2017, 07:00 UTC)
thePHP.ccTesting Keeps Me From Gettings Things Done (24.5.2017, 07:00 UTC)
SitePoint PHPHow to Use Laravel Mix in Non-Laravel Projects (23.5.2017, 18:00 UTC)

If you, like me, just want to get up and running on a project as quickly as possible, you probably don’t want to spend time configuring build tools like Webpack. Laravel Mix solves this problem, and makes asset compiling incredibly easy, but what if you want to use it on a non-Laravel project? This article shows you how to accomplish that.

Potion vector illustration

What Is Laravel Mix?

Laravel Mix, formerly Elixir, could be defined as an API wrapper for Webpack. It has a fluent syntax and is generally easy to use. Setting up versioning, hot reloading, and asset building/compiling is a breeze, and requires only a single configuration file and a few lines of code.


For most of my projects, be it clients or personal, I choose Laravel, but I recently had a client who wanted the ability to edit pages and content on their website, he wanted a CMS. I decided to give OctoberCMS a try, considering that it's based on Laravel.

I set up File Watchers from PhpStorm, but it didn’t work as well as running Laravel Mix. After a week of using File Watchers, I tried pulling Laravel Mix from a Laravel project, and the result feels exactly like it should.


For this tutorial, I assume that you have basic knowledge of managing JSON files and that you have NPM and Node installed on your system.

If you want to use versioning and hot reload, you’re required to use PHP, and Composer.

To verify that you have NPM and Node, you can run the following in your terminal:

node -v
npm -v

You should see versions for both Node and NPM.

Note: You can also use Homestead Improved which comes with all of this installed. If that's confusing to you, clear things up with our book!

Continue reading %How to Use Laravel Mix in Non-Laravel Projects%

Voices of the ElePHPantInterview with Larry E. Masters (23.5.2017, 14:12 UTC)

Show Notes

The post Interview with Larry E. Masters appeared first on Voices of the ElePHPant.

Paul M. JonesControllers and Domain Exceptions (23.5.2017, 12:00 UTC)

A few months ago I had a great email conversation with a correspondent about how to handle business logic exceptions in his controller code. His message follows, lightly edited for brevity and clarity:

I think controller has single responsibility – to mediate communication between caller’s context and actual business logic services. (I believe business logic services should be unaware of caller’s context, be it HTTP request or CLI.)

Given that services should be unaware of who called them, they should not throw HTTP-specific exceptions. So instead of throwing a Symfony HttpNotFound Exception, the service would throw ObjectNotFound (which is HTTP agnostic) in cases where DB record could not be found.

Yet at the same time the logic that converts exceptions to HTTP responses expects HTTP-specific Symfony exceptions. This means that the exception thrown by service needs to be transformed into Symfony exception.

One of solutions I see to this is that the controller could take that responsibility. It would catch domain exceptions thrown by service and wrap them into appropriate HTTP exceptions.

class FooController
    public function fooAction()
        try {
        } catch (ObjectNotFound $e) {
            throw new NotFoundHttpException('Not Found', $e);
        } catch (InvalidDataException $e) {
            throw new BadRequestHttpException('Invalid value', $e);
        } // ...

The downside I see with this approach is that if I have many controllers I will have code duplication. This also could lead to big amount of catch blocks, because of many possible exceptions that could be thrown.

Another approach would be to not have try/catch blocks in controller and let the exceptions thrown by service bubble up the stack, leaving the exception handling to exception handler. This approach would solve the code duplication issue and many try/catch block issue. However, because the response builder only accepts Symfony exceptions, they would need to be mapped somewhere.

It also feels to me that this way the controller is made cleaner, but part of controllers responsibility is delegated to something else, thus breaking encapsulation. I feel like it’s controllers job to decide what status code should be retuned in each case, yet at the same time, cases usually are the same.

I truly hope you will be able to share your thoughts on this and the ways you would tackle this.

If you find yourself in this situation, the first question to ask yourself is, “Why am I handling domain exceptions in my user interface code?” (Remember: Model-View-Controller and Action-Domain-Responder are user interface patterns; in this case, the user interface is composed of an HTTP request and response.) Domain exceptions should be handled by the domain logic in a domain-appropriate fashion.

My correspondent’s first intuition (using domain-level exceptions, not HTTP-specific ones) has the right spirit. However, instead of having the domain service throw exceptions for the user interface controller to catch and handle, I suggest that the service return a Domain Payload with domain-specific status reporting. Then the user interface can inspect the Domain Payload to determine how to respond. I expand on that approach in this post.

By way of example, instead of this in your controller …

class FooController
    public function fooAction()
        try {
        } catch (ObjectNotFound $e) {
            throw new NotFoundHttpException('Not Found', $e);
        } catch (InvalidDataException $e) {
            throw new BadRequestHttpException('Invalid value', $e);
        } // ...

… try something more like this:

class FooController
    public function fooAction()
        $payload = $this->service->doSomething('foo');
        switch ($payload->getStatus()) {
            case $payload::OBJECT_NOT_FOUND:
                throw new NotFoundHttpException($payload->getMessage());
            case $payload::INVALID_DATA:
                throw new BadRequestHttpException($payload->getMessage());
            // ...

(I am not a fan of using exceptions to manage flow control; I’d rather return a new Response object. However, I am trying to stick as closely to the original example as possible so that the differences are more easily examined.)

The idea here is to keep domain logic in the domain layer (in this case, a service). The service should validate the input, and if it fails, return a “not-valid&r

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

LinksRSS 0.92   RDF 1.
Atom Feed   100% Popoon
PHP5 powered   PEAR
ButtonsPlanet PHP   Planet PHP
Planet PHP