Dealing with alternative directory structures in ZF2

I just started diving into Zend Framework 2 after using Zend Framework 1 and even its early predecessors for years.
And boy, things have changed! But after some initial reading I think I already see some major advantages, not in the last place the ModuleManager which really allows developers to create independent modules and share them with the community.

Anyway on to the actual subject of this post: directory structure. A standard ZF2 application has the following directory structure:

config
data
module
public
vendor
init_autoloader.php

public contains index.php and your .htaccess, plus your public web resources such as images javascript and css files.

In a shared hosting environment running Plesk the directory structure is like this:

httpdocs (this is the webroot)
private
statistics
subdomains
etc.

We don’t want to put everything in the httpdocs directory, because that’s the public directory and is accessible from the outside world. In a Plesk environment the private directory is used for application level files that aren’t supposed to be accessible from outside. So the solution is pretty simple:

  • Upload the contents from the public directory into httpdocs
  • Upload the other directories (config, data, module, vendor and init_autoloader.php) into private

After that you have to change the index.php file (in public) to make sure it searches for the init_autoloader.php script in the right location. By default this is sitting at the same level as the public directory, outside the public directory and hence this statement at the top of index.php:

chdir(dirname(__DIR__));

This line should be changed into:

chdir(dirname(__DIR__) . '/private');

And that’s it, now your ZF2 app should run within this Plesk style directory structure. Pretty easy, but I hope it’s helpful to someone.