Aug 122012
 

This post will show you how to create a simple view helper in Zend Framework 2.

In this example, our view helper will simply return the full, absolute URL of the current page/request.

<?php
// ./module/Application/src/Application/View/Helper/AbsoluteUrl.php
namespace Application\View\Helper;
 
use Zend\Http\Request;
use Zend\View\Helper\AbstractHelper;
 
class AbsoluteUrl extends AbstractHelper
{
    protected $request;
 
    public function __construct(Request $request)
    {
        $this->request = $request;
    }
 
    public function __invoke()
    {
        return $this->request->getUri()->normalize();
    }
}

You’ll notice that this particular helper has a dependency — a Zend\Http\Request object. To inject this, we’ll need to set up a factory with the initialization logic for our view helper:

<?php
// ./module/Application/Module.php
namespace Application;
 
use Application\View\Helper\AbsoluteUrl;
 
class Module
{
    public function getViewHelperConfig()
    {
        return array(
            'factories' => array(
                // the array key here is the name you will call the view helper by in your view scripts
                'absoluteUrl' => function($sm) {
                    $locator = $sm->getServiceLocator(); // $sm is the view helper manager, so we need to fetch the main service manager
                    return new AbsoluteUrl($locator->get('Request'));
                },
            ),
        );
    }
 
     // If copy/pasting this example, you'll also need the getAutoloaderConfig() method; I've omitted it for the sake of brevity.
}

That’s it! Now you can call your helper in your view scripts:

The full URL to the current page is: <?php echo $this->absoluteUrl(); ?>

Note: I’ll be covering the details of the getViewHelperConfig() method and how ZF2 uses the ServiceManager to handle view helpers, controller plugins, etc in a later post.

Aug 102012
 

Sometimes I like to show someone my working/development copy of a project without having to commit/push or upload to a server.

Note: This post builds on my dynamic virtual hosts post, however the concept described here can be used to simply make port 80 on your local machine public from any connection, regardless of your virtual host configuration.

To accomplish this, I lease a static IP from my ISP (you could probably use dynamic DNS, too), and point *.ip.evan.pro to my static IP at home. I can then turn on and off port 80 forwarding when I want to show something to a friend (actually, I leave port 80 forwarded and toggle it wih iptables). In the Nginx, I simply added .ip.evan.pro to the server_name directive so it reads: server_name .dev .ip.evan.pro; (ServerAlias on Apache).

With port 80 open, I can point people to http://myproject.ip.evan.pro/ and it will load right up.

Note: Many broadband ISPs in the US such as Cox and Comcast tend to block port 80 on residential connections. I happen to be using a CenturyLink (formerly Qwest) VDSL connection, and they’re kind enough to let me use my ports however I’d like.

So using *.ip.evan.pro is great when I’m at home and have control over forwarding port 80, but I also wanted to be able to show people my working copy no matter where I was connected from (public wifi, friend’s house, conference, office network, etc).

Continue reading »

Aug 102012
 

I’ve been meaning to blog about this topic for quite a while, but like most other I kept putting it off. However, a recent exchange on Twitter has shown there might actually be some demand for this, so here it is.

Over the years, I’ve slowly evolved my web development environment for efficiency and convenience. A couple of years ago, I realized that I was sick and tired of having to create a new virtual host and edit my host file for every single project, and decided to come up with a solution. Two years later, and I couldn’t imagine working without my awesome dynamic virtual host setup. It’s well-worth the few minutes you’ll invest getting it working.

So just how cool is it? Well, let’s take a look at how simple it is for me to start a new project:

Continue reading »

Jul 182012
 

This post is intended to familiarize you with the various features of the new Zend Framework 2 ServiceManager component along with some simple examples.

So, what is the ServiceManager? Basically it’s a registry, or container (the proper term is service locator) to hold various objects needed by your application, allowing you to easily practice Inversion of Control. The service manager holds just the information needed to lazily instantiate these objects as they’re needed. So if you were thinking ‘services’ such as those composing a service layer, you might be better off thinking of the service manager more as an “object manager” or “instance manager”.

Continue reading »

Jul 182012
 

So you’re all excited to try out ZF2. You clone the skeleton, install some modules, maybe even follow Rob Allen’s excellent ZF2 tutorial, and finally, start building your application. Now, if you’re a former ZF1 user or refugee from another framework, you might be troubled at this point by the fact that, at first glance, ZF2 doesn’t appear to take into consideration environment-specific configuration values (e.g., development, testing, staging, production). Luckily, this is not the case!

Continue reading »

Jul 152012
 

This is meant to be a short, easy-to-follow tutorial to help you get started with Zend Framework 2.0 and add perhaps one of the most common modules, ZfcUser. By the end of this tutorial, you’ll have a simple ZF2 application with user registration and authentication capabilities.

Prerequisites

I’m going to assume you have the following installed:

  • PHP 5.3.3+ (with pdo-sqlite or pdo-mysql)
  • A web server and knowledge of how to set up a virtual host
  • Git

If you have PHP 5.4+ you don’t even technically need a web server to try out ZF2, as you can simply use PHP’s new built-in development web server.

A note about composer

While composer is a supported way of setting up the skeleton, I am choosing to simply use git for the sake of this tutorial. In my opinion, this keeps things simpler, and easier to debug if anyone has issues following my tutorial.

Continue reading »

Jun 292012
 

The new Zend\Db in Zend Framework 2 has a handy feature which allows you to specify your own entity/model class to represent rows in your database tables. This means you can tell Zend\Db to return each row as a populated instance of your own custom objects. Keep in mind that this is simply a convenience feature, and not meant to serve as a fully-featured ORM. If you’re looking for a full-blown ORM, have a look at Doctrine 2.

For this demonstration, let’s assume the following table:

CREATE TABLE `book` (
   `isbn10` VARCHAR(10) NOT NULL,
   `isbn13` VARCHAR(13) NOT NULL,
   `author` VARCHAR(50) NOT NULL,
   `title` VARCHAR(255) NOT NULL,
   `year` INT(4) NOT NULL
);

Continue reading »

Jun 192012
 

Today I gave a talk at Go Daddy’s annual TechFest conference about building modular web applications with Zend Framework 2.0. The talk went well, and the audience was surprisingly engaged and inquisitive! I would like to thank Go Daddy, and specifically Kurt Payne for allowing me to speak at this awesome conference.

If you attended my talk and have any comments or feedback, please feel free to comment on this post. Thanks!

Getting started with git-bisect in 60 seconds

 Posted by on June 4, 2012  General  1 Response »  Tagged with: ,
Jun 042012
 

There’s a million posts about using git-bisect already, but not many that will have you using it productively in under a minute.

First, find a commit where things were working and a commit where things are broken (cef2f9c9 and e0f7bef7, respectively in our example) and start the bisect:

[user@workstation zf2 (master)]$ git bisect start

Now tell git about the good and bad commits:

[user@workstation zf2 (master|BISECTING)]$ git bisect good cef2f9c9
[user@workstation zf2 (master|BISECTING)]$ git bisect bad e0f7bef7
Bisecting: 107 revisions left to test after this (roughly 7 steps)
[3511807a26cdcf63b2d9b48a046f9ec264cc4523] ZF-1897 XmlRpc Resolved issue with leading/trailing whitespace in chunked HTTP response sync svn r24150

So now that you’ve given Git a good and a bad commit, it starts the bisect. Basically, Git is going to check out commits between the two commits you gave it using binary search. For each one, you test for the issue you’re having and tell Git if the commit it checked out is good or bad:

[user@workstation zf2 ((3511807...)|BISECTING)]$ git bisect good
Bisecting: 55 revisions left to test after this (roughly 6 steps)
[3b3d98daa1a0f16f4253ab18c70230a3295c4132] [Filter] Remove dependency with legacy Zend\Loader
[user@workstation zf2 ((3b3d98d...)|BISECTING)]$ git bisect bad
Bisecting: 25 revisions left to test after this (roughly 5 steps)
[ec1574f386e50483cf7922f3ecbc993430f59ee7] [#1388] Added assertSame assertions

Rinse and repeat, and after a few iterations, Git will tell you exactly which commit introduced your problem. It’s that easy!

When you’re all done, simply run git bisect reset.

May 112012
 

First, I should point out that the title of this post is a bit of an intentional misnomer. There’s really no such thing as “module-specific” anything in ZF2, so what we’re really talking about is the topmost namespace of the controller being dispatched. So in the case of MyModule\Controller\SomeController, the topmost namespace would be MyModule. In most cases, this will be the name of a given module.

UPDATE: The information in this post is still correct and applicable, but I’ve made a very simple module called EdpModuleLayouts to make it even easier.

Here’s how you can easily switch the layout (or perform any other arbitrary logic) for a specific module in Zend Framework 2.0 (as of d0b1dbc92):

<?php
namespace MyModule;
 
use Zend\ModuleManager\ModuleManager;
 
class Module
{
    public function init(ModuleManager $moduleManager)
    {
        $sharedEvents = $moduleManager->getEventManager()->getSharedManager();
        $sharedEvents->attach(__NAMESPACE__, 'dispatch', function($e) {
            // This event will only be fired when an ActionController under the MyModule namespace is dispatched.
            $controller = $e->getTarget();
            $controller->layout('layout/alternativelayout');
        }, 100);
    }
}

This event listener will only be triggered if an ActionController under the MyModule namespace is dispatched, so you do not need to perform any additional logic to check which “module” or namespace the controller being dispatched is under.

Keep in mind, as of writing this, ZF2 is still in beta. There are plans to add a convenience layer to the framework before the GA release which will likely make common tasks like this much simpler.

See also: Rob Allen’s post on module specific bootstrapping in ZF2