Jump Start PHP Environment (2015)

Chapter 2 The Programming Environment

There are two types of environment in the context of programming: the application environment, and the programming environment. We’ll be covering the application environment in a later chapter. This part of the book will talk about the programming environment, explaining IDEs (integrated development environments) and suggesting which ones to try, explaining coding standards and exploring some command line basics. In this chapter, it all becomes slightly more technical.

The programming environment includes―but is not limited to―the people you interact with, your operating system, your code editor or IDE (more on this later), your coding standards, and generally everything that helps or hinders your work during development. In other words, the programming environment is the programmer’s environment.

Skip this chapter if you:

·        have a good IDE picked out and don’t intend to switch

·        know where to find help for any programming problems

·        are following coding standards already, whether you’re in a team or flying solo

·        are familiar with the command line

Read this chapter if you:

·        are using a simple text editor to code or don’t know any IDEs

·        think coding standards are unnecessary

·        have no idea where to obtain genuinely useful advice for problems you might encounter

·        are unfamiliar with the command line and/or think it's unnecessary because alternatives exist

A Good IDE Is Worth Its File Size in Gold

The old adage of “being worth its own weight in gold” stands true for IDEs, or integrated development environments. IDEs are advanced programs for writing code, and at the end of this section we'll present a few decent options for you to try.

You may be familiar with text editors such as TextMate or Notepad. There are code-oriented alternatives such as Sublime Text and Notepad++ that make coding much, much easier by offering commonly known language constructs and helping you autocomplete some statements so that memorizing entire programming language commands is a thing of the past. Most even offer syntax highlighting, which makes code more readable by applying different colors to certain keywords and phrases that are programming-language-specific. See Figure 2.1 for code without syntax highlighting, and Figure 2.2 for an example with syntax highlighting.

Text editor without syntax highlighting

Figure 2.1. Text editor without syntax highlighting

Text editor with syntax highlighting

Figure 2.2. Text editor with syntax highlighting

Yet without exception, all text editors pale in comparison to good IDEs. An IDE is a powerful program―it’s like a text editor on steroids containing in-depth references to your given language of choice, often helping you by providing suggestions and coloring the text to make it more readable, as well as by:

·        helping you automatically apply coding standards to your code (we'll discuss coding standards later in this chapter)

·        allowing you to move code up and down or left and right, and easily duplicate it without having to cut and paste

·        supplying coding templates so you that can avoid rewriting the same commands over and over again

·        providing intricate search facilities that treat various commands and functions as entities and not just text, meaning you can do things like tell the IDE “Show me where this function first appears”

·        integrating bug checkers, standards checkers, and testing suites, all of which ensure that your application is running properly without you having to constantly recheck it

·        integrating version control systems so that you can maintain different versions of your code from the IDE, ensuring that you always have infinite “undo” capabilities when programming (more on version control in Chapter 5)

·        enabling you to connect to databases and remote servers right from the IDE, letting you easily debug your database or test the code on your remote server (for example, a company’s server at headquarters while you’re at home) to ensure it will work fine come Monday morning

And much, much more.

So, which IDEs are a good option for PHP development?

In my own order of preference:

PhpStorm

PhpStorm is a commercial IDE, meaning it’s neither open source nor free, but it’s well worth the price. It offers everything that’s been mentioned above and more, and works on all operating systems flawlessly, whether you’re on Linux, Windows, or Mac OS X. It has been written about on SitePoint extensively if you’d like to see some reviews, handy shortcuts, hacks to become even more efficient, other people’s approaches, and so on. JetBrains―the company who makes it―also tends to give out free licenses now and then, and you can qualify for one by maintaining an open-source project. Alternatively, keep an eye out for surveys and reviews on SitePoint’s PHP channel as we sometimes give out licenses, too.

Commercial support means quick responses from the support team, rapid development (updates come out regularly with many new features), and a guarantee of continued maintenance. Note that PhpStorm allows for a 30-day free trial, and if you’re still yet to be convinced after a month, they’ll often extend your trial license.

Pros:

very fast, feature-rich, stable (never crashes), cross-platform support

Cons:

costs money, can be resource-intensive, and is unfriendly to older computers. See requirements at https://www.jetbrains.com/phpstorm/help/system-requirements-and-installation.html.

NetBeans

NetBeans, an open-source IDE, sports almost all the features of PhpStorm and is its nemesis. I had used NetBeans for two years before transitioning to PhpStorm, and recommend it to everyone who needs a good IDE but isn't prepared to pay for a commercial one.

NetBeans is slightly slower than PhpStorm and more resource-intensive. It is cross-platform, relatively stable, and very reliable. The group behind it was acquired by Oracle, and while some see this as a bad omen, I feel it only cements the reliability of the current version.

Pros:

free, feature-rich, reliable, cross-platform, open source

Cons:

Oracle-owned, lacks commercial support, slower to adopt new features

Zend Studio

Zend Studio is made by the company “in charge” of PHP (though, it’s been acquired by Rogue Wave software, whose name may appear in certain places where Zend used to be). Zend is the company who first brought PHP into existence, and who provide official certification for the language.

Zend Studio is a commercial IDE that’s a bit pricier than PhpStorm, but it offers a free trial so you can give it a spin before committing to it. It has many of the same features of PhpStorm and NetBeans, with some exceptions, as well as some of its own. Tools for easier mobile app development (available in Netbeans and PhpStorm via plugins) are built into Zend Studio, and its own Apigility platform (a service for creating APIs based on their Zend Framework) has a native Zend Studio driver, too. Don’t worry if you’re unfamiliar with any of these terms, they’ll be covered later in the book.

Another perk is the built-in support for Zend Server―a special kind of server program used to run your PHP application and provide various analyses on running code and advanced debugging capabilities. Zend Server is a paid product, though, so if you want to use it in Zend Studio, you’ll need to purchase a license. There’s some basic information about Zend Server here: http://www.sitepoint.com/getting-know-zend-server-7/.

If your goal is to become the most “official” PHP developer you can be, with certificates and a total knowledge of officially endorsed tools and services, Zend Studio is right for you. Otherwise, I’d recommend either of PhpStorm or NetBeans.

Pros:

great commercial support due to being owned by Zend; feature-rich, cross-platform, and integrates with other Zend products nicely

Cons:

expensive, resource-intensive, and unstable; can be slow

Here are some other options you can research at your own leisure, a mix of commercial and free:

·        Komodo IDE: http://komodoide.com/

·        Eclipse with PDT: https://eclipse.org/pdt/

·        Aptana Studio: http://www.aptana.com/

·        phpDesigner: http://www.mpsoftware.dk/phpdesigner.php

There’s also a list, ordered by popularity, at http://www.sitepoint.com/best-php-ide-2014-survey-results/.

Whichever IDE you choose, stick with it for at least a couple of months. The learning curve is often high, and you might feel overwhelmed by all the options when you first start using it. In time you’ll become used to everything it offers, even if you’ll only be using 10% of its functionality in your first 100 days of code. There’s nothing wrong with switching IDEs at a later date, but give each one you try a reasonable chance.

At this point in time, it’s unnecessary to download and install an IDE. This book is very light on code, and you’ll only need one when we reach the later chapters.

Warning: Beware IDEs with WYSIWYG

One item IDEs do not and should not provide is WYSIWYG (What You See Is What You Get) editing. Dreamweaver, an IDE by Adobe, is one such tool. It’s infamous for letting you get started easily because it allows you to pull in elements from a toolbar and drop them visually onto the screen, helping you “build code” as if playing with Lego blocks. Yet the code it generates is often suboptimal and bloated, containing more code than necessary and slowing a website down. What’s more, by skipping the real coding part, you're effectively holding yourself back. You'll be unable to read anyone else's code, and you'll have a far tougher time learning to solve problems on your own.

Dreamweaver is not the only WYSIWYG editor, but it’s by far the most popular one. If you run into an IDE that supports WYSIWYG, I wholeheartedly recommend you run in the opposite direction.

The Importance of Coding Standards

Coding standards are rules applied to code so that it's consistent across the entire project. For example, if Jim writes code this way:

if ($purchaseWasCompleted)

    $this->succeed();

else

    $this->error();

but Mike writes code like this:

($purchaseWasCompleted) ? $this->succeed() : $this->error();

and Joanna writes it as follows:

$pwc = $purchaseWasCompleted;

if ($pwc)

{

    $this->succeed();

} else {

    $this->error();

}

they have all written the same code differently. Now, if Jim reads through Mike’s code, it might take him longer to go through it purely because he’s used to his own way of writing. If they both examine Joanna’s code, they’ll be confused by the amount of code it took her to produce the same outcome as them in a different form.

If, however, they agree on a coding standard, they’ll all produce the exact same code. Once they grow used to the standard, they’ll be able to read each other’s code more fluently, noticing bugs and reusing features with ease without any apparent language barriers.

Many IDEs have the ability to automatically apply certain coding standards; for example, the current favorite in the PHP world is the PSR-2 coding standard, and all the IDEs mentioned have built-in mechanisms to at least check for it, if not apply it automatically and autocorrect your code. With PSR-2 (PSR stands for PHP Standard Recommendation), code such as this:[1]

class Test {

    protected $name;

    public function __construct($name) {

        $pointlessSum = 3+4;

        if ($name)

            $this->name = $name;

        else

            $this->name = "Default";

    }

    public function echoName() {

        echo $this->name;

    }

}

would be reformatted to look like this:

class Test

{

    protected $name;

    public function __construct($name)

    {

        $pointlessSum = 3 + 4;

        if ($name) {

            $this->name = $name;

        } else {

            $this->name = "Default";

        }

    }

    public function echoName()

    {

        echo $this->name;

    }

}

Much more readable, isn’t it? And all it took was some blank lines and spacing changes―that’s more or less everything a coding standard does. Trivially simple, but vitally important. Standards also dictate other aspects, such as uppercase/lowercase letter conventions when naming classes and variables (notice the uppercase Test in the previously mentioned code); the position of curly braces in logic constructs such as if, for, and others; and more.

We strongly recommend using PSR-2. It’s what the vast majority of high-quality projects out there use, making your coding style instantly compatible with that of many, many developers. It will also prepare you for reading their code fluently. With an IDE, this becomes incredibly easy. For example, in PhpStorm, you would go to File > Settings > Editor > Code Style, and select PSR1/PSR2 (PSR-2 improves upon PSR-1, so this option applies both). Note that, depending on your version of PhpStorm, you might also have to select Set From in the Code Style windows. In other IDEs, it's as simple as googling for the phrase “PSR-2 in EDITOR” where EDITOR is your IDE of choice. It will yield a plethora of results.

The Command Line / Terminal

Finally, let’s briefly look at the command line or terminal. First, a clarification on the terminology.

On Windows, the program you can see in Figure 2.3 is called the command prompt or command line:

The Command Prompt says “Hello”

Figure 2.3. The Command Prompt says “Hello”

You run it by typing “cmd” or “command prompt” into the search box. In this, its most basic shape, it allows you to execute commands that run Windows programs, and either produce some written output (such as the echo command seen in Figure 2.3 that produces the output “Hello!”), or open applications you’re already familiar with (if you type “notepad” into the command prompt and hit enter, the Notepad application will open). The command line has alternative implementations such as Cmder (seen in Figure 2.4) or Console. They are prettier versions that essentially perform the same task, but make certain actions such as copy pasting, tabbing interfaces, and selecting text simpler.

Cmder says “Hello”

Figure 2.4. Cmder says “Hello”

On Mac and Linux machines, the program is called Terminal. To run it on either of these systems, open search and input “Terminal” and it should pop right up. It performs the same functions as the Windows Command Prompt, though has different commands. For example, the command to show the content of a directory (folder) in Windows is dir while on Apple and Linux it’s ls.

Any developers worth their salt need to become friendly with the command line / terminal to maximize their potential. There are common workarounds to most command line commands and various shortcuts you can take at first, but it’s never too long before those become more cumbersome and limiting instead of useful.

The differences between the Windows and the non-Windows versions are unimportant because you’ll be using the Apple/Linux-specific commands, even on Windows. We’ll show you how in Chapter 4.

The Community

As a final element of the programming environment, Iet’s discuss asking for and providing help. The community around your programming language of choice is among the most important factors when learning to code. Being able to quickly and reliably obtain answers to problems you encounter can mean the difference between making or missing a deadline in a commercial project.

No developer knows the entire list of their preferred programming language's commands by heart. I’ve been programming in PHP for almost a decade, and I still regularly look up even the basic commands. Real knowledge lies not in knowing the commands by heart, but in knowing where to quickly find them.

That said, here are some resources you should bookmark in your browser right now under a folder titled “PHP Help.”

PHP Mentoring

PHP Mentoring aims to assist people in finding mentors and disciples. If you’re an expert, you can mentor newbies, and if you’re a beginner, you can find a mentor. A mentor will tell you about best practices, analyze your code and provide feedback, point out your mistakes, and set you on the right path whenever you stray. There are no fees associated with this; it’s a purely voluntary effort by some good souls. If you’re a total newbie, I suggest you apply for mentorship as soon as you flip this book’s last page.

PHP.net Documentation

The official site of the programming language is chock-full of code samples, with user comments further examining and explaining them. You will likely get little use out of it by just wandering through the pages aimlessly, but whenever you become stuck and need to check out a function or command, your first Google result will likely be PHP.net. If you’re on a poor connection, or are often offline, there’s also an offline version of these docs that you can download stand-alone or as a Google Chrome application.

Various Forums

The SitePoint forums are an excellent resource with legions of people willing to help. You’re almost guaranteed to receive an answer in minutes if you go into enough details with the question. The forums are gamified, meaning they have badges and points awarded to those who post there, encouraging the community to participate.

The StackExchange network is a consortium of context-specific (ranging from programming to chess and cooking) question-and-answer websites, made by the same people who built the software that powers the SitePoint forums. Being also gamified, this form of reward system entices users to participate more than usual, so one can gain an answer to a well-formed question in a matter of hours, if not minutes. There are three major subsites you should bookmark for the full experience:

·        StackOverflow (http://stackoverflow.com/) is the most popular generic programming Q&A site. You can ask about any language here, as long as it’s about development. You can also ask questions not dealing with programming directly, such as inquiries about IDEs, servers, and so on.

·        Programming (http://programmers.stackexchange.com/) focuses solely on programming problems. If you get stuck coding, this is where you ask your questions, but make sure you google extensively first. Most of the newbie problems already have solutions online, and you won’t be hard-pressed to find them.

·        Code Review (http://codereview.stackexchange.com/) is used for having your code reviewed by other people and receiving feedback. It’s important to accept feedback for what it is: apply the positive, brush off the negative, and learn from the constructive.

There are many other subsites in the network. Just look at the footer of any of these three―the full list is there. You might even find some that interest you outside of programming.

These resources listed will be of endless help to you at the beginning of your PHP journey. As soon as you feel even the least bit comfortable in basic PHP programming, I encourage you to seek out some intermediate and advanced tutorials by visiting SitePoint’s PHP channel.

Summary

In this chapter, we dealt with coding standards, code editors, communities, and other approaches that make coding more comfortable for ourselves, along with the people inheriting our code. Having a good coding bon ton from the get-go will produce exponential improvements down the road as these helpful habits become muscle memory. Remember: good habits are just as difficult to break as bad ones!


[1] Don’t worry if you don’t understand this code, it’s just for demonstration purposes.