Advice for Programmers Beginning with PHP

2014-02-24

When learning a new programming language, it can be really difficult to get off the ground. Sure, it is easy to find books on any programming language, but it can sometimes be difficult to find answers to questions like these: What are the go-to libraries/modules/packages I should know about? What are the latest code format standards? Where on the web can I find the best resources for learning this language?

I recently started learning Python and these were some of the questions I had. Having spent the last several years programming with PHP, I decided to write a short guide that will hopefully answer some of these questions to programmers just starting out with PHP.

1. Find a Book

There are tons of PHP books and I honestly don't know which one to recommend. The best I can do is recommend a book\ebook\online tutorial that covers PHP 5.3+. The latest release of PHP is 5.5 and 5.6 is just around the corner but I feel that some of the biggest changes to PHP occurred in 5.3. There are some  great new features in PHP 5.4--including square bracket array syntax--and PHP 5.5 has some new features worth learning so any book that covers 5.3+ should be a good starting place to learn basic syntax.

2. Code Formatting

The  PHP Framework Interop Group (PHP-FIG) has a  series of standards known as PSRs that act as guidelines for code formatting, tabs vs. spaces, class naming, auto-loading, etc. While your PHP scripts will still run if you don't follow these guidelines, I highly recommend following them. While not everything I write is PSR-2, I try to be very PSR-2(ish). The sooner you understand PSR-0 and PSR-4 autoloading, the sooner you will master the use of Composer.

The idea behind the group is for project representatives to talk about the commonalities between our projects and find ways we can work together. The PHP-FIG Website

3. Dependency Management

Composer is the package installer\updater and dependency manager that PHP has been waiting for. In the past, most people would hunt the web for a PHP library that does XYZ. When they found it, they would download a zip file with the files and plop it into some folder in their project. When they wanted to use the library, they would manually add some ' require' or 'include' calls to a PHP script to load the classes contained within the files. But what happened if you wanted to update the library later or it contains a class with the same name as another class? I'll tell you--it was a mess.

Composer relies upon git repositories to install\update PHP packages. You can browse the available packages at  Packagist.org. Many packages rely on other packages in order to work properly so each package contains a composer.json file where these dependencies are specified so Composer knows what needs to be installed. That is just a very basic description of what Composer does. If you'd like to learn more (and you should!), check out the Getting Started documentation.

4. Choosing a Framework

You don't have to use a framework to develop applications with PHP, but I definitely recommend using one because it can save you a lot of time and prevent you from re-inventing the wheel. Many developers have solved common application development problems by writing open source frameworks you can use. There are a lot of well-developed modern frameworks with Composer integration. To name a few:  Laravel (My personal favorite), SymfonyZend 2SlimSilex, and Aura (a series of independent packages). I truly enjoy using Slim for smaller projects though it is not limited to small projects. After all, you only need to add vendor\package items to your composer.json file to expand your application's functionality.

PHP that doesn't hurt. Code happy & enjoy the fresh air. The Laravel website

5. Testing

PHPUnit is the go-to unit testing framework for PHP. Many--if not all--of the modern PHP frameworks are testable with PHPUnit and contain features that help you integrate unit testing in your own application because there is a big drive to write testable code.

6. Additional Thoughts

It is one thing to know the syntax of writing a PHP class or function, but it is another thing to know how to divide responsibilities between classes\functions. It isn't uncommon to find bloated class methods or bloated global functions that aren't reusable outside of their intended narrow scope (See: WordPress) in other people's PHP code. This is a problem that can arise in any programming language but it is good to cover it here anyway because I hate running across bloated code that isn't reusable at all or functions that have a thousand exit points. I think the principles of  SOLID programming can help prevent you from writing poor code. I don't have these memorized, but I understand the underlying message enough to stop myself from writing nasty code in most cases (we are all guilty from time to time).

I hope I covered everything accurately and I gave you just enough information to help you get started on your path to becoming a modern PHP developer. If I missed anything or I said something wrong, I'm sure it'll appear on twitter somewhere. Maybe it will even be the source of some  PHP Drama. I sure hope not.

Useful Links

<?php

echo "Welcome to PHP... er, Hello World.";

Laravel array_get() Helper Function

2013-11-07

I'll be honest; the only reason I am writing about this is to remind myself that this helper function exists. I get tired of always having to use isset() to check if an array index is defined. I quite often write lines of code that look like this:

$name = isset($names[$id]) ? $names[$id] : 'No name';

This alternative is easier to write and looks better too:

$name = array_get($names, $id, 'No name');

Sure, it really only saves me a few characters in this example but it looks cleaner.


Why I Define all my Laravel Routes Individually

2013-08-25

I know it can be pretty tempting to construct a controller in Laravel then define a single route to send several requests to that controller. For instance, I might define a controller route like this:

Route::controller('user', 'UserController');

I used to define routes like this because it felt like a quick way to tell my application how to handle any request made to /user/*, but not anymore. Now I define every single route individually. Sure, I still build controllers to group related actions together, but I wouldn't get the same level of control over my routes using Route::controller() that I do from defining each route individually.

I believe the greatest benefit to defining every route is that I can then build an entire application without ever hard-coding a single URL. For example, let's say I have a user profile route defined like this:

Route::get('user/{username}', ['as' => 'user.profile', 'uses' => 'UserController@getProfile']);

In this example, I have given the route a name and told it which controller method to use when handling requests. Whenever I want to construct a link to the specified route in my application, I just do the following:

<a href="{{ URL::route('user.profile', [$user->username]) }}" >{{ $user->username }}'s profile</a>

The result will look something like:

<a href="http://example.com/user/benjaminkohl" >benjaminkohl's profile</a>

Now think about the kind of power that gives me. If I later decide that a user's profile should be viewed from a different URL, I only have to change ONE line of code in my entire application. I just modify my existing route to look something like this and the links to a user profile on my site will automatically start using the new URI structure:

Route::get('user/profile/{username}', ['as' => 'user.profile', 'uses' => 'UserController@getProfile']);

Suppose I have various routes pertaining to users but I only want to assign a filter to one of them. It is as simple as adding the filter to that route. I don't have to mess with defining filters in my controller's constructor; it's all laid out right there for me in my routes file.

Route::get('user/dashboard', ['as' => 'user.dashboard', 'before' => 'auth', 'uses' => 'UserController@getDashboard']);

This concept comes in handy especially with route groups. I may have a group for the user dashboard routes that all use the same auth filter to protect certain pages from being viewed by guests. But what if there are certain routes within the dashboard that should also be limited to users with certain privileges? I can just create a new filter and add it to any route that needs it. All the routes in a group will inherit any filters assigned to the group, but they may also have their own filters. That kind of functionality could get very messy and difficult to spot at a glance if I were to define route filters inside the controller.

In summary, using Route::controller() or Route::resource() may seem like time savers, but I guarantee it is worth the extra time initially to just define each route individually.


Custom Pagination Views in Laravel 4

2013-07-23

I recently needed to create some custom-styled pagination links for a Laravel application and I figured I would share what I learned about that process. Laravel has two default pagination views: simple and slider. The pagination style setting is specified in your application's /app/config/view.php file. It will look something like this:

'pagination' => 'pagination::simple'

To begin developing your custom pagination view, create a subfolder called "pagination" (or whatever) in your application's views folder then create an empty view file called "mine.php". You can tell your application to use your new view file by modifying the aforementioned setting like so:

'pagination' => 'pagination.mine'

The simplest way to begin developing your view file is to copy and modify one of the existing default pagination views. Both files can be found in the following folder:

/vendor/laravel/framework/src/Illuminate/Pagination/views

For this demonstration, I'll be modifying the simple view but feel free to use whichever one you want as your base. The simple view looks like this:

<?php
    $presenter = new Illuminate\Pagination\BootstrapPresenter($paginator);
    $trans = $environment->getTranslator();
?>
<?php if ($paginator->getLastPage() > 1): ?>
    <ul class="pager">
        <?php
            echo $presenter->getPrevious($trans->trans('pagination.previous'));
            echo $presenter->getNext($trans->trans('pagination.next'));
        ?>
    </ul>
<?php endif; ?>

Once you have copied the contents of one of the default view files to your new "pagination.mine" view, you can begin making adjustments to the code. Once you're done editing the code, you can just output your pagination links as usual and you'll see your custom style in action! If you'd like to learn more about the various classes and methods used in the pagination views, refer to the Laravel Pagination API docs.

If you'd like to override the default text used on the previous and next buttons, you can do so in the /app/lang/<lang_abbr>/pagination.php file. All you need to do is modify the values stored in that array.

<?php 
return array(
	/*
	|--------------------------------------------------------------------------
	| Pagination Language Lines
	|--------------------------------------------------------------------------
	|
	| The following language lines are used by the paginator library to build
	| the simple pagination links. You are free to change them to anything
	| you want to customize your views to better match your application.
	|
	*/
	'previous' => 'Back',
	'next'     => 'Forward',
);

That's it for this tutorial. I hope you found it helpful!


Yet Another Site Rebuild

2013-07-22

I've decided to rebuild my website... again. About six months ago, I rebuilt my website using Laravel 4 BETA and while I love Laravel very much, I never built an admin panel for the site so I never ended up updating the site at all. With that in mind, I decided to rebuild my site using Craft. I love Craft's use of TWIG, its intuitive routing and its easy to use control panel. It is everything I could ask for in a CMS.

For the front-end, I used Foundation. I am not a designer so I don't mind using a front-end framework to dictate a few rules while allowing me some freedom to deviate from the default styles. I was able to easily override styles using SASS.

As far as the site colors go, I'm probably going to be accused of ripping off the color from the Laravel website (it looks pretty similar to me and I'm colorblind) but I actually used an online tool to generate a color scheme based on a photograph of my son who was wearing an orange striped shirt.

So anyway, here's hoping I actually start publishing some tutorials here and other bits of helpful information.


My name is Benjamin Kohl and I am a web developer from Grand Rapids, MI.