Screencasts, Symfony2, Tutorials

Developing with Symfony2, part 1: Setting up shop

I’m pleased to announce that, after some technical difficulties, I have uploaded a Symfony2 screencast to YouTube. It’s part one of a series in which I’ll be walking through the development, from the ground up, of a working Symfony2 application… look for more installments in the coming weeks.

This screencast walks through a few of the basics:

  • downloading Symfony2 Standard Edition using git
  • using composer to install the framework dependencies
  • best practices for preserving privacy of sensitive information
  • making the logs/ and cache/ directories writable (note: if you can’t get this working, a good ol’ chmod -R 777 app/cache/ app/logs/ ought to get you started)
Uncategorized

I, for one, welcome our new PHP 5.4 overlords

Is that joke old yet? Anyway, with PHP 5.4 officially released yesterday, I’m very excited about the new traits implementation which, in a nutshell, allows a class to import specific functionality in the form of implemented methods.

In my post on interfaces, I explained that interfaces are like a contract, promising to deliver specific functionality without promising exactly how they will deliver it. Traits take it a step further, providing a contract that not only promises functionality, but also specifies an implementation, to be mixed in to or “exhibited” by concrete classes. To borrow an old example:

In the example above, instantiations of FooObject would have access to the tag() method imported from the Taggable trait. This is a very powerful feature, one which will provide a workaround to some of the limitations of PHP’s single inheritance hierarchy and let developers create an even more powerful toolkit of code snippets to call on, reducing development time and (hopefully) increasing productivity.

And that’s not all that 5.4 is bringing to the table. Here’s a pithy tweet summing up the new release:

php 5.4 in a nutshell

Symfony2

Demystifying Symfony2 Controllers

I came across this Stack Overflow question a couple days ago, asking about the proper place to put business logic in a Symfony2 application: whether it belongs in the controller, a service, or elsewhere. Actually, that’s quite a common question that I see: what, exactly, belongs in the controller? The documentation has this to say:

A controller is a PHP function you create that takes information from the HTTP request and constructs and returns an HTTP response (as a Symfony2 Response object). The response could be an HTML page, an XML document, a serialized JSON array, an image, a redirect, a 404 error or anything else you can dream up. The controller contains whatever arbitrary logic your application needs to render the content of a page.

Now, let me sum that up for you: the controller is meant to construct and return a response. That’s… it, really. It’s not meant for heavy lifting. Way too often, I see controller actions that are completely loaded down with code, heavy with business logic that would be better-suited (not to mention more reusable) in a service, or even a custom entity repository. And frequently, I’ll see controller actions that try to deal with more than one thing (like a view action also handling search results — with the search code written out in the action, of course). As a result, I’ve come up with a short checklist for writing your controllers:

  1. Controllers are meant to be thin. Think of a controller as the glue of your application, a lightweight connection between a model and a view… emphasis on “lightweight.” That means that as much code as possible should be offloaded to services, repositories, etc. I’ll cover those topics in a future post.
  2. Controllers should only handle one thing. Symfony2 has a great feature that lets you render embedded controllers, meaning that any one controller should only perform a specific action: viewing or editing a resource, for example, or retrieving search results.

I did say short, didn’t I? Learn to love and live by the principles of separation of concerns and and DRY: if you’re copy-pasting code to more than one place in a controller, it’s probably time to start thinking about how you can refactor to bring all that duplicated work into one easy-to-maintain location.

Another thing: the base controller available in the Symfony2 FrameworkBundle provides a great collection of helpful methods to get you started, but you can feel free to extend it or ignore it as you please. Because controllers can be any PHP callable, you’re not required to use the FrameworkBundle’s controller at all. In fact, because the FrameworkBundle is technically an optional dependency, it’s considered good practice to provide your own self-contained controller classes instead of using the base controller if you intend to make your code available to other users in the community.

And as always, the community abounds with examples of great code. The FriendsOfSymfony projects are a good place to start looking if you’re wondering about best practices: just dive into any repository and start looking at how they’ve built their controllers. I’m also happy to answer any questions you might have; feel free to leave a comment or shoot me an email to djstobbe@gmail.com. Happy coding!

Edit: the link to wikipedia’s entry on “Don’t repeat yourself” was broken. It’s fixed now.

Further Reading on Symfony2

Code Snippets

HashBang: PHP console app microframework

One of the irritating constants of the development process is the necessity of doing the same things over and over again. Every time you deploy a Symfony2 project, for example, there’s pretty much a checklist that has to be followed:

  1. Pull from the remote repo
  2. Run bin/vendors install if any of the vendor requirements have changed
  3. Update the database schema if your entities have changed
  4. Clear the opcode cache
  5. Clear Symfony2’s production cache

And if you forget a step, it takes even longer to go back and correct it. So, I wrote a handful of shell scripts that automate some common processes; namely, testing and deployment. They worked fine until coworkers start coming to me and saying things like, “I really don’t want to have to run the vendors install every time if I KNOW that the vendors haven’t changed,” or, “Your deploy script requires a manual update of the database schema; can you add a flag that I can use locally to do it automatically?”

I’m no bash scripting expert, so when I realized that it was going to take longer to figure out how to update my deployment script than it would to rewrite it as a PHP CLI script, I sat down and hacked something out quickly. Then I looked at my testing script, and found that I’d be copy-pasting a lot of the same code to deal with command-line arguments and switches. So, I came up with another solution.

HashBang is a console app microframework that I hammered out in a couple of hours one night. Its purpose is to abstract away some of common code in a CLI script — dealing with optional and required arguments, and supporting command-line switches — and let you focus on what your script should actually be doing. You simply tell your HashBang app what arguments and switches to expect, and pass it a closure to execute when you call go(). Check it out:

That’s it. Obviously, it’s not as full-featured as some of the other solutions out there might be, but it’s quick and dirty and gets the job done.

Software Design

PHP Interfaces: what they are, and why you should be using them

A lot of people have been using PHP for a long time. It makes sense; it’s a language that has been designed for and makes it easy to put content (and I use the term loosely) on the web. Unfortunately, just because something has been designed for a specific purpose doesn’t mean that it does it well. Call it another can of worms, but PHP before major version 5 (with a reworked object model) was miserable to work with on any level beyond “here is my procedural code, please show me my banner ad filler… I mean, website now.”

Fortunately, steps have been taken to fix this, and the later versions of PHP (starting with 5.0, but especially since 5.3) have started providing us with tools to actually develop, instead of just code (more on that distinction another day). One of the features introduced with PHP 5 (and the one I want to focus on in this post) was the concept of object interfaces. From the documentation:

> Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.

Put simply, an interface is a contract between the concrete implementation of a class and any code that uses it. It says, in effect, “I promise that I will implement these methods, and that they will be publicly accessible to your code.” That’s the entirety of the contract; an interface doesn’t (and in fact, can’t) dictate the implementation of the contracted methods, just their existence. If a class implements the interface iCookable with methods bake() and checkTemp(), nothing is stopping it from implementing bake() to launch carrier pigeons and checkTemp() to release a bunch of balloons into the sky.

Given an effort to remain semantically compatible, however, a class that implements a given interface can expose a public API and hide all of its implementation details: the entire internal workings of the class could be thrown out and rewritten, and code that uses the class would never even have to know or care.

A practical example

So why should you care about all of this? Well, imagine that you are composing a class to add tags to an object (which could represent a blog post, a user comment, or something else entirely). Without using interfaces, your tag() method might look something like this:

That’s all well and good, but what if the object passed to the method doesn’t provide a publicly accessible addTag() method? Furthermore, what if $object is not actually an object at all, but a string or an array? Even if you’re writing the entire codebase yourself, accidents still happen, and if not, you lose even more control. You could do something like this…

… but this is tedious, and violates the principle of Don’t Repeat Yourself if you have to add the same code over and over again for every method relating to your taggable objects. A better solution is to create an interface that contracts to provide methods needed for tagging.

Note that while it’s good practice to explicitly declare visibility for your class methods and properties, method signatures defined by an interface are inherently public, so I figure that you can get away with saving a few keystrokes.

Also note that I’ve gone ahead and added a basic docblock that documents both the arguments the method should take (in this case, a string representing the tag we’re adding to the object), and what it should return (in this case, nothing). Since PHP does not allow us to hint a method’s return type or the more primitive variable types (string, integer, boolean, etc), docblocks are a great way to encourage the semantic compatibility we were talking about earlier.

Okay, now we have an interface that guarantees the methods we need for tagging. Back in our tag() method, let’s implement it:

Simple as that. We no longer have to wonder if $object will, in fact, be an object, or whether it will provide the methods we need to add tags to it, and we don’t have to couple the tag() method to a concrete implementation of a taggable object. Any class can implement our TaggableInterface, and if the implementation is rational, our code can expect to be able to add tags to that class until the end of the world.

tl;dr

You can use interfaces to ensure that the functionality your code needs will be accessible, without tying yourself to a particular implementation of that functionality.

Uncategorized

Introducing skid: stupid-simple unit testing for PHP

I have a confession to make: I’m tired of PHPUnit. It’s overly complex for what I want to do: assert that a piece of code either passes (returns true) or fails (returns false). $this->assertTrue(/*...*/); is pretty much the only assertion I ever use these days, because it’s a lot easier for me to write $this->assertTrue(array_key_exists($key, $array)); than to try to remember, “Okay, $this->assertKeyExists… no, that’s not it. Um, $this->assertArrayHasKey, got it.” And don’t even get me started on exception testing. How is this…

more expressive or less confusing than this?

So, I wrote my own. I call it skid (find it on github). It’s very simple and rough, but it does what it needs to: pass the script a file and it will run the test methods and tell you if the assertions passed or failed. Some things skid doesn’t do:

  • Class mocks. Just create a simple concrete class that extends the abstract class or interface that you want to test, with as much or little logic as you want in the implemented methods. Voila, you have yourself a mock.
  • Unnecessarily verbose assertion methods. In fact, there’s just one: ASSERT(). The script does a little voodoo so that it can display exactly what code was in the assert, because knowing that a bit of code returned false without an easy way to tell what the code was┬áisn’t very useful.

I wouldn’t really recommend putting skid to any kind of production use (like I said, very simple and rough); I consider it a proof of concept for a better world of unit testing, where unit tests actually HELP you with testing, instead of just adding MORE work to your already overloaded task list.

Maybe the way I look at unit testing is not for everyone. If you have something to add (or maybe if you just think I’m an idiot), use the comment box below!