Bruno ŠkvorcGetting to Know Zend Server 7 (22.7.2014, 16:21 UTC)

Zend Technologies is the company which funds the development of the Zend Engine (the engine PHP is based on), as well as Zend Framework and some other projects like Apigility. They also build proprietary software of high professional caliber, designed for high intensity PHP work in large companies - software like Zend Studio and Zend Server - though both are excellent tools for solo devs as well. In this post, we’ll be taking a look at the latter.

What is Zend Server?

Zend Server is, essentially, a locally-run web application which helps you run, deploy, debug and production-prepare other applications you write. It’s more than a developer helper, though - you can install it on your production servers and have it take care of hosting, clustering, file distribution and more.

It automatically installs Zend Framework (both version 1 and 2 for some reason) and Symfony 2, and supports GUI-based management of other libraries and projects for total ease of use. All operating systems and platforms are supported, and you can install it alongside Apache or Nginx - your choice. You can have it pull in PHP version 5.4 or 5.5, and it will do the rest on its own once you run the installation script.

The latest version of ZS, version 7, comes in several licenses and flavors, so give those a read if you’d like to know about the differences.

The concept of Zend Server might be a bit too abstract to grasp right now if you’ve never encountered it before, so let’s just walk through it instead.

Continue reading %Getting to Know Zend Server 7%

thePHP.ccHHVM: The New PHP? (22.7.2014, 07:00 UTC)
Bruno ŠkvorcBest Practices REST API from Scratch – Introduction (21.7.2014, 16:00 UTC)

The current internet ecosystem has literally been invaded by APIs, and for good reasons. By using third party APIs in your products or services, you have access to a ton of useful features — such as authentication or storage services — that can benefit both you and your users. By exposing your own API, your application becomes “part of the mix” and will be used in ways you’ve never thought before… if you do it the right way, obviously.

In this two part series I’ll show you how to create a RESTful API layer for your PHP applications, using a collection of real world best practices.

The full source code of this project will be available at the end of part 2.

A pleasant UI for developers

First of all, an API is a user interface for developers, so it must be friendly, simple, easy to use and of course pleasant; or else it will end up being another piece of digital junk out there.

Documentation, even in the form of a simple but well written README file, is a good place to start. The minimal information we need is a summary of the service’s scope and the list of methods and access points.

A good summary can be:

Our application is a simple contact list service that manages contacts with linked notes. It has two object types, contacts and notes. Each contact has basic attributes such as first name, last name, and email address. Also, each contact can have a number of markdown-formatted notes linked to it.

Then, it’s a good idea to make a list of all the resources and actions that we are going to implement. This can be seen as the equivalent of wireframing for visual applications. Following the key principles of REST, each resource is represented by a URL, where the action is the HTTP method used to access it.

For example GET /api/contacts/12 retrieves the contact with id of 12, while PUT /api/contacts/12 will update that same contact.

The full list of methods is displayed below:

URL                           HTTP Method  Operation
/api/contacts                 GET          Returns an array of contacts
/api/contacts/:id             GET          Returns the contact with id of :id
/api/contacts                 POST         Adds a new contact and return it with an id attribute added
/api/contacts/:id             PUT          Updates the contact with id of :id
/api/contacts/:id             PATCH        Partially updates the contact with id of :id
/api/contacts/:id             DELETE       Deletes the contact with id of :id

/api/contacts/:id/star        PUT     

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

Bruno Škvorc7 More Mistakes Commonly Made by PHP Developers (20.7.2014, 18:00 UTC)

Back at the end of June, TopTal, the freelance marketplace, published a post about 10 Most Common Mistakes PHP Programmers Make. The list wasn’t exhaustive, but it was well written and pointed out some very interesting pitfalls one should be vary of - even if I wouldn’t personally list the mistakes as very common.

I encourage you to give it a thorough read - it has some truly valuable information you should be aware of - especially the first eight points. A couple days back, Anna Filina expanded on the list with seven new entries. While less specific and common, her points still carry weight and should be considered when developing.

X More Mistakes PHP Developers Often Make

I was asked by someone from TopTal to take a look at their list and potentially contribute, and some of our followers on social networks expressed an interest in seeing the list continued, too, so I’d like to take this opportunity to add some of my own entries to this list that I repeatedly need to warn my team members or followers about.

Continue reading %7 More Mistakes Commonly Made by PHP Developers%

Anna FilinaOn ethics and optimism (20.7.2014, 15:54 UTC)

It really annoys me when people say that discussing ethics on social media doesn’t change the world. That is just cynical and pathetic, and these people want to drag others into inaction. Discussing allows you to question your morals and refine your opinions. You eventually act on those values and change the world.

A single person can’t change the world? That’s where you are wrong. You can write a blog post to influence hundreds, who in turn will influence thousands. You can buy shoes for one homeless and start a trend of altruism. You can organize a conference and change a city forever.

Perhaps these cynics think that you should either fix EVERYTHING wrong with the world immediately or go home. They are jealous cowards who can only feel adequate if they can convince you that you can’t achieve anything either.

I’m an optimist, but many confuse me with an idealist. I know that perfection doesn’t exist, but many people create imaginary limitations. They consider something unrealistic or impractical, until I push the limit and prove them wrong.

P.S.: the image above is the one I took of NASCAR’s Kyle Busch who duct taped his car to stay in the race. He did a great job that day.

Bruno ŠkvorcVagrantfile Explained: Setting Up and Provisioning with Shell (19.7.2014, 16:00 UTC)

In the first part of this article, we showed you how to create a Vagrant base box, installing the latest Ubuntu 14.04 LTS in the virtual machine to use it as the guest operating system.

In this part you will learn how to setup a development environment using Vagrant, which you can use and reuse in your development. Note that while you can use the box we created in the previous part for the remainder of this post, you don’t have to - this will all work on any Ubuntu based Vagrant box.

The Vagrantfile

The primary configuration location for any Vagrant development environment is a file called Vagrantfile which you need to place in your project’s folder.

The configuration syntax of this Vagrantfile is Ruby, but you do not need to be a Ruby programmer or have any knowledge of the programming language to write this configuration file. You’ll mostly do basic variable assignment in the configuration.

Every configuration option you will need you can place inside this file.

Let’s go ahead and create a test folder called vagrant-tutorial and inside this folder create the file named Vagrantfile so your folder structure looks like this:


About provisioning

The primary purpose of Vagrant is to have a base virtual machine and to give you the framework for creating automatic software installations and configurations in the virtual machine.

By letting Vagrant handle the provisioning of software, it also gives you the flexibility in configuration and more importantly, makes this process repeatable and automatic.

Vagrant doesn’t care how you provision the virtual machine, it offers multiple options ranging from basic shell scripts to software automation managers such as Puppet, Chef or Ansible. You can even configure it to use multiple provisioners at the same time.

Ofcourse there’s always the possibility to vagrant ssh into the base virtual machine and install your required software manually, but that defeats the purpose of Vagrant and all the flexibility it offers when provisioning a box.

Provisioning prerequisites

Before we can start provisioning the base box, we need to set a few required options in our configuration file.

Vagrant API version

Vagrant uses API versions for its configuration file, this is how it can stay backwards compatible. So in every Vagrantfile we need to specify which version to use. The current one is version 2 which works with Vagrant 1.1 and up. Let’s write this block in our Vagrantfile.

Continue reading %Vagrantfile Explained: Setting Up and Provisioning with Shell%

Anna FilinaCommon PHP Mistakes (19.7.2014, 00:53 UTC)

I was recently asked by one of my readers to give feedback on the following article he read: 10 Most Common PHP Mistakes. It is well written and very thorough. Most of the tips are specific to PHP, others are about web programming in general or database performance. It’s a very good read. I was also asked to contribute to this list, so here are 7 more tips. I found these very common in my code reviews or various audits.

11. Forgetting to cache

Websites can be slow due to a variety of reasons. Adding a cache layer not only improves the user’s experience, but also tremendously reduces the load on your servers. There are many ways to cache and you can combine different cache types: query cache, Redis, Varnish, etc.

12. Allowing SQL injection

Security is easy to overlook, especially when starting out. SQL injections are extremely dangerous. Let’s say you write this in your code:

"SELECT first_name FROM users WHERE id = " .$input['user_id'] . ";"

It is possible for the user to provide a malicious input, such as:


Once your query is concatenated, it will end up looking like this:

SELECT first_name FROM users WHERE id = 13; DELETE FROM users WHERE 1;

You can protect yourself by filtering the input, such as making sure that it’s a number. Another good practice is to always use prepared statement when using PHP variables in SQL. Example:

$stmt = $pdo->prepare("SELECT first_name FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $input['user_id']);

This will make sure that a user simply cannot “break” out of the query. More on prepared statements.

13. Disabling error reporting

When I first started writing PHP in 2003, I was annoyed when my PHP errors or notices showed up on the web. I simply disabled error reporting in production, while keeping them on my local machine to help debug my code. This was a mistake. If any error should happen in production, the user won’t see it, but I won’t know that something is broken either. For this purpose, you should keep the error reporting. Don’t show it to the user but log it to a file, which you can then view. This can be done easily via the php.ini file:

display_errors: off
log_errors: on
error_log: logs/errors.log

14. Staying on the same page after the form was processed

If the form contains errors, you will probably display the same page again and highlight the errors. That’s good. But then if the form was successful and processed, such as creating a database record or charging a credit card, you need to redirect the user. Think of it as adding sugar to your coffee. Each time you refresh the page (your user can choose to accept the resubmit warning), another spoon of sugar is added. Do it enough times and you’ll have sugar with a hint of coffee, or charge the credit card 10 times. Redirecting the user lets you prevent “replaying” the action. Redirect like this:


15. Reinventing the wheel

The PHP community is incredibly active. There are countless packages that you can install using Composer. Tools include e-mailing, file system, templating, caching, parsing various formats, handling multilingualism, unit testing, etc.

Many people don’t realize how many functions come out of the box with PHP. There are thousands of functions that can replace hundreds (or more) of lines in your code, so dig around.

There are also many frameworks that help you organize your code and take a lot of the repetitive, tedious work off your hands. Find a top X list, read some reviews on each and take a pick.

16. Letting your scripts run forever

Don’t assume that your script will always finish quickly. Perhaps your script talks to a server that is taking long to respond. Perhaps the user decided to upload a very big file. Perhaps you have a database congestion and your script is just waiting on its turn. Expect the unexpected and use set_time_limit().

Extra trick: determine which scripts should be lighting quick, such as upvoting a comment, and which should be allowed to run longer, such as image processing. Set a time limit based on expected maximum. If there is an unexpected delay,

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

Bruno ŠkvorcSocial Network Authentication: Twitter and Facebook (18.7.2014, 16:00 UTC)

In the previous parts of this series, we created our initial interfaces, set up our Google+ login functionality and talked about how we can merge our accounts together. In this article, we will integrate Twitter and Facebook within our application. You will see a lot of similarities with the Google+ article, so if you could follow that one easily, you won’t have much trouble with this one. If you haven’t read that article yet, I suggest you read it first before continuing this article.

You can view the code for all the articles on this Github page.

Twitter login

Once again, we start off by creating the following directory: src/SitePoint/SocialLogin/Twitter. Within this directory, we create the TwitterLogin class. This class implements the SocialLoginInterface interface which we created in the first article. Make sure a property called service is available to store our service in.

Like Google+, Twitter has some specific needs to make sure we can log in. So make sure we have the following 3 properties present in the class:

  • Client id
  • key
  • callback URL

Since all 3 properties are required for our application to work, our constructor will receive these 3 variables as parameters and set the properties.

Up until now, your code should look the same as the first example in the Google+ article.

Our next step is to create our Twitter service. We will be using the same OAuth library and will set up a connection within the init method.

Before we can start, we have to add some use statements to the top of our class.

Continue reading %Social Network Authentication: Twitter and Facebook%

Paul M. JonesSoccer, Development, and The Value Of Teamwork (17.7.2014, 19:04 UTC)

The lesson of soccer is that individual effort will often suffice when things are relatively easy. But in order to surmount the more difficult challenges, you will almost always need reliable teammates of one sort or another.

I assert the same is true in development efforts. A single developer working alone can do good work, but a team of frontend devs, backend devs, devops, and DBAs can do stuff that is truly amazing. Combine your comparative advantages instead of trying to do everything yourself. Via Vox Popoli: Calcio is life.

Paul M. JonesAction-Domain-Responder, Content Negotiation, and Routers (17.7.2014, 16:55 UTC)

While talking about Action-Domain-Responder on the Crafting Code Tour, one of the common questions I got was: “Where does content negotiation happen?” My response was always: “Where does it happen in Model-View-Controller?” That opened up a discussion on how content negotiation is a tricky bit that can go in different places, depending on how you want the concerns separated, and is not a problem specific to ADR.

However, I’ve not really been satisfied with that outcome. I enjoyed the question and the discussion, but it never seemed to resolve itself. We were left with this tension between resource conservation and proper separation of concerns. Should negotiation happen in the the Action (Controller), the Domain (Model), or the Responder (View)?

At first it seems like this is clearly a (re)presentation issue, and as such ought to go in the Responder or View. But if the Responder cannot present an acceptable content type for the request, that means we have done a lot of work in the Domain to build objects that will be discarded in favor of a “406 Not Acceptable” response. This is not a good use of our limited resources.

Perhaps the Domain is the place for negotiation? I think we can dismiss this outright. The Domain should not be in charge of returning different presentations of its data.

Finally, we might try negotiation in the Action (Controller). Here we examine the request, and query the Responder to see what content types it can present in responses. (Alternatively, we embed the available content types in both the Action and Responder, duplicating that information somewhat.) If the negotiation fails in the Action, we skip the Domain work and instruct the Responder to return a “406 Not Acceptable”. But that means the Action is now responsible for at least a little bit of the response-building logic. It’s not horrible, but it does not seem as clean as it could be.

After thinking about this for a while, I am beginning to think it is reasonable to perform what I will call a “first filter” on the Accept header at the Front Controller level, specifically in the Router. We already consider the Router as a guard to map incoming requests to appropriate Actions, inspecting the path, HTTP method, and other request information. Inspecting the acceptable types seems a reasonable addition to these elements.

A full content negotiation at the Router level is probably overkill. Really, all the Router needs to know is what content types are provided through particular Route (whether an MVC or ADR one). The matching logic can do a naive check of the Accept request header to see if one of the provided types is present with a non-zero “q” value. If none of the types is present, the Router can move along to the next route, possibly tracking the failure so a Dispatcher can directly invoke a Responder for routing failures. This way, the Router never invokes a non-matching Action, thereby conserving the Domain resources. If the match is successful, the Responder can do the “real” content negotiation work, using an Accept header value passed to it as input from the Action along with the Domain data.

As a proof of concept, I have modified the Aura.Router library to recognize “accept” specifications on the route, and the tests indicate it seems to work just fine.

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