Unique filenames when uploading in Zend Framework

This is typical Zend Framework; needing a simple file upload as part of a Zend Form, I turned to the built in helpers and yes, it’s easy to upload a file with minimal additional code. So far so good.

But it defaults to uploading the file with the original filename and to overwriting existing files. I cannot remember a time when this was the behaviour I wanted from a file uploader; I always want to preserve existing files instead of overwriting them, and I usually want to give it some additional information in the filename or folder path – things like account or user IDs and timestamps for example, or just random hashes.

Eventually managed to find a way of customizing it that didn’t require three times the code saved by using Zend Framework in the first place, with grateful thanks to Dean Clatworthy:

$post = $request->getPost(); // This contains the POST params
 
        if ($request->isPost()) {
            if ($form->isValid($post)) {
 
                $upload = new Zend_File_Transfer_Adapter_Http();
                $filename = $upload->getFilename();
                $filename = basename($filename);
 
 
                $uniqueToken = md5(uniqid(mt_rand(), true));
                $filterRename = new Zend_Filter_File_Rename(array('target' => '/path/to/uploads/' . $uniqueToken.$filename, 'overwrite' => false));
                $upload->addFilter($filterRename);
 
                if (!$upload->receive()) {
                    $this->view->message = 'Error receiving the file';
                    return;
                }
 
                $this->view->message = 'Screenshot(s) successfully uploaded';
            }
        }

Unique filenames when uploading using Zend_Filter_File_Rename (Zend Framework).

Advertisements

Zend Framework 2 – blech

It’s been a while since I paid any attention to what they were doing in ZF2; I’d been aware of the discussion and some of the plans way back, but last time I checked in there was nothing much to see yet unless you were involved directly with the effort.

So I stopped by today and was impressed to see that ZF2 is in production and there to download as 2.0.6.

I read through the new getting started tutorial and experienced a sinking feeling. I’ve always had this love/hate relationship with Zend Framework. Not so much with the software, actually, as the project as a whole. Since starting to use it back in 2007, I’ve found it badly documented, constantly shifting and often seeming to lack a coherent direction. Because it changed so much and relatively quickly in the early days (and had massive new features parachuted in without much explanation in later versions, like the Application object) it’s always been hard to know the best way to do things, particularly when you need to grab it quickly to use on a new project after working on an existing one for an extended period.

There is lots of good stuff in ZF2 – I’m really pleased to see unit testing front and centre in the getting started, for example, and I like the new more convenient form rendering methods.

But I’m shocked at how lengthy and verbose the getting started tutorial is, just to get to the point where you’re printing out some records on a page. I’m not saying ZF should have scaffolding or that scaffolding is actually particularly useful to have; on the other hand, I ask myself, do I really have to type all that in, especially when other frameworks are so much more expressive? Or more realistically, copy/paste it all every time you need it. The routing code is amazingly ugly with an extraordinarily low signal to noise ratio – just imagine how much boilerplate you’ll be scrolling through in a real app just to read the dozen or so bits of actual information in that.

This is not a technical criticism, incidentally, it’s an aesthetic and usability thing. I’m not disputing the architectural decisions; the guys who write and maintain ZF are way above me as programmers. But as an average, reasonably experienced web developer, I want to write code that I like to look at, code that is “user-friendly” for the developers in the same way that the UI should be user-friendly for the end users.

Zend Framework.

Functional testing with Selenium and PHPUnit

Installing this stuff is simple in principle but a bit of a pig in practice

1. Install pear
download http://pear.php.net/go-pear.phar
sudo php /tmp/go-pear.phar

2. Install PHPUnit
pear config-set auto_discover 1
sudo pear channel-discover pear.symfony.com
pear install --alldeps pear.phpunit.de/PHPUnit
sudo pear install phpunit/DbUnit
sudo pear install phpunit/PHPUnit_Story

3. Install PHPUnit selenium package
pear install phpunit/PHPUnit_Selenium

4. Install Selenium Server
Download a distribution archive of Selenium Server. http://seleniumhq.org/download/
Unzip the distribution archive and copy selenium-server-standalone-2.9.0.jar (check the version suffix) to /usr/local/bin, for instance.
Start the Selenium Server server by running java -jar /usr/local/bin/selenium-server-standalone-2.9.0.jar

Then execute test file using
phpunit --colors testSubmitLoginForm test.php

PHPUnit 3.7.9 by Sebastian Bergmann.

..

Time: 30 seconds, Memory: 5.25Mb

OK (2 tests, 3 assertions)

All sounds simple but in reality several hours of dicking around with Pear channels may ensue before final success…

Useful links:
http://seleniumhq.org/download/
http://net.tutsplus.com/tutorials/php/how-to-use-selenium-2-with-phpunit/#close=1
http://www.phpunit.de/manual/current/en/selenium.html
http://devzone.zend.com/1014/acceptance-testing-of-web-applications-with-php/

Preventing xdebug truncating its var_dump results

When inspecting a deeply nested data structure using var_dump; xdebug does nice code formatting and syntax highlighting making it distinctly more pleasant to read. But it “helpfully” truncates the information beyond a certain depth, which really sucks when you need to check the details deep in the data structure.

Luckily all you need to do is add these lines to php.ini to make it output the whole thing:

xdebug.var_display_max_children=-1
xdebug.var_display_max_data=-1
xdebug.var_display_max_depth=-1

Dependency injection

Knowing that objects should be decoupled from one another is one thing. Actually doing it in practice is quite another, but I found some great blog posts that I found really helpful – for example:

>The problem with most dependencies is the way that code handles and interacts with them. What I really mean is the problem is in the code and not the dependency. 
>
> — Ryan at Potstuck.com: [PHP Dependency Injection](http://www.potstuck.com/2009/01/08/php-dependency-injection/)

[Fabien Potencier](http://fabien.potencier.org/), the creator of the Symfony framework for PHP, has become something of an evangelist for dependency injection in the PHP world and made available some awesome [presentations](http://www.slideshare.net/fabpot/dependency-injection-with-php-and-php-53) and [articles](http://fabien.potencier.org/article/11/what-is-dependency-injection)

The issue is not that dependencies are bad; a web application cannot function without some sort of session persistence or access to a database of some sort, for example. These are necessary dependencies and will always be there. But the problem is how your classes get at their dependencies such as session storage, cache and database.

A common approach might be to inherit the database handle from a base class or set it in the __construct() method then reference it where needed. This works well enough, but leads to precisely the sort of coupling we don’t want:

[php]
class User
{
private $conn;
public function __construct()
{
$this->conn = DB::getInstance();
}
public function getUsers()
{
$query = $this->conn->prepare("SELECT * FROM users");

}
}[/php]

But here we still have the problem that the User class goes and gets the database handle from another class in the application. Scale this up in a significant web application and you can end up with a chaotic spider’s web of dependencies between classes that is hard to unravel. This directly breaks the “separation of concerns” paradigm, and also creates significant problems when trying to write unit tests for these classes.

Dependency injection is based on Inversion of Control, colloquially known as the Hollywood Principle; don’t call us, we’ll call you. In this case, we move the dependency outside of the class definition and ‘inject’ it into the class by one of various means

The three standard methods are

Constructor injection:
[php]$user = new User(DB::getInstance());[/php]

Setter injection:
[php]$user = new User();
$user->setDB(DB::getInstance());[/php]

Property injection:
[php]$user = new User();
$user->conn = DB::getInstance();[/php]

Each of these breaks the internal dependency of the User class on the DB class and makes it much easier to test the User class as a single unit of work, at the cost of one extra line of code wherever the User class is instantiated.

This might not be ideal in complex situations. For example, there may be several dependencies to inject, such as database cache or session storage container; this makes the constructor method signature more cluttered if you’re using constructor injection, or adds additional lines of code in the other two cases. It also makes it necessary to understand all the required dependencies of a class and explicitly set them everywhere you use it. In practice this could make the application considerably harder to work on.

There is another pattern that can be used to alleviate this sort of concern; using a factory or container to manage the dependencies in one place. So for example

[php]
class Container
{
public static function makeUser()
{
$user = new User();
$user->conn = DB::getInstance();
$user->storage = new SessionStorage(‘memcache’);
$user->cache = new Cache(‘memcache’);
return $user;
}
}
[/php]

And typical use would look something like this:

[php]
$user = Container::makeUser();
$users = $user->getUsers();
…[/php]