The Zend Framework Bootstrap Made Simple (Part 1)

When you’re creating a new project with the Zend Framework, unlike other frameworks, you need to do more legwork. This isn’t necessarily a bad thing, but it can sure slow you down when you’re trying to plough through a project.

I really enjoy using it, as it has a very well structured approach – and I like structure – it clearly lays out a file-system structure for modules, controllers, actions, forms, models and so on. It has good, but basic, tooling, allowing for modest project initialisation. But despite all this, it still requires a healthy investment on our part to get a proper foundation in place to use it productively.

In a recent project I encountered this situation and felt that I mustn’t be the only one to do so. As I plan to keep using Zend Framework I want to work around this situation and get as much productivity out of it as possible right from the get go. But how to do this?

Bootstrapping

Well the primary focus for me is bootstrapping. It provides the majority of the core services that every project needs, from routing, data source connections, authentication, authorisation, navigation, caching and so on. So it stands to reason that it’s a good place to start. So I want to cover what should go in to a good working bootstrap.


When you’re creating a new project with the Zend Framework, unlike other frameworks, you need to do more legwork. This isn’t necessarily a bad thing, but it can sure slow you down when you’re trying to plough through a project.

I really enjoy using it, as it has a very well structured approach – and I like structure – it clearly lays out a file-system structure for modules, controllers, actions, forms, models and so on. It has good, but basic, tooling, allowing for modest project initialisation. But despite all this, it still requires a healthy investment on our part to get a proper foundation in place to use it productively.

In a recent project I encountered this situation and felt that I mustn’t be the only one to do so. As I plan to keep using Zend Framework I want to work around this situation and get as much productivity out of it as possible right from the get go. But how to do this?

Bootstrapping

Well the primary focus for me is bootstrapping. It provides the majority of the core services that every project needs, from routing, data source connections, authentication, authorisation, navigation, caching and so on. So it stands to reason that it’s a good place to start. So I want to cover what should go in to a good working bootstrap.

I want to look at what initialisation resources it should contain and how it should be configured, to save both you and me time in the future. Now I’m not claiming that this is the best approach – as your needs are likely to be different from mine. And like anything, this is a work in progress – which you can find on github.com.

But what it definitely is, is a start and what other place to start from, than the beginning. So, what’s in it?

  • Cache
  • Routes
  • Database
  • Navigation
  • Placeholders
  • Logging

Now that’s a hell of a list and there’s no way that I’m going to be able to cover all of it in just one post. Well, I could but it would be one really long post. So this is going to span three posts so that it’s comprehensive enough to use properly. Ok, you could cheat and go right to the [github repository][2] and grab the code – but that wouldn’t be any fun, now would it?!

What Are We Covering?

In this, the first post in the series, we’re going to cover caching as it’s arguably what will underpin a lot of the performance gains later on – and we all love performance, don’t we? (maybe it’s just me). That will round out the first part.

In the second part, we’re going to look at routing, databases and navigation. Finally, in the third part, we’re going to look at views, pagination and logging as a nice way to finish.

I hope that you enjoy it. I hope that you get a lot out of it. But most of all, I hope that you send through your thoughts and feedback, both on the articles and also on the code. So, with that, let’s begin.

What is an Application Bootstrap?

Applications that implement the Front Controller pattern route all requests through a central script which then determines how to satisfy the request accordingly. For those new(er) to Zend Application development, this is handled through the Zend Application component. According to the Zend Framework manual, Zend application:

…is broken into three realms:

  • Zend_Application: loads the PHP environment, including include_paths and autoloading, and instantiates the requested bootstrap class.
  • Zend_Application_Bootstrap: provides interfaces for bootstrap classes. Zend_Application_Bootstrap_Bootstrap provides common functionality for most bootstrapping needs, including dependency checking algorithms and the ability to load bootstrap resources on demand.
  • Zend_Application_Resource: provides an interface for standard bootstrapping resources that can be loaded on demand by a bootstrap instance, as well as several default resource implementations.

The aspects that we’re going to be focusing on here are Zend_Application_Bootstrap and Zend_Application_Resource. What we’re going to be doing is extending Zend_Application_Bootstrap_Bootstrap and creating a series of resource methods. Then, our default application bootstrap, for future projects, will then extend that class and, by the power of OOP, automatically have these methods available.

Create the Default Project

So, go through the normal process of tooling a Zend Framework application and us zf.sh to create the basic project with:

zf.sh create project magic-bootstrapping

Now that we have a basic project in place, open up the default application ini config and add the following line near the top of the file and add the following line:

autoloaderNamespaces[] = "Common_"

This will load the class namespace that we’re about to create. Following this, save and close the file and create the following directory structure under /library/.

Common/Application/Bootstrap/

In there, create a file called Bootstrap.php and add the code below:

<?php

class Common_Application_Bootstrap_Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{

}

After this is done, open up the default Bootstrap.php file, under /application/ and change the default class definition from:

<?php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{

}

to:

<?php

class Bootstrap extends Common_Application_Bootstrap_Bootstrap
{

}

Load your new application in the browser and you will see the default Zend Framework page just like normal. Nothing different, yet, but we have the basis of our new bootstrap file in place and we’re ready to add in the first plugin resource – caching.

Caching

One of the most important aspects of an application is, arguably, caching. To quote a good friend, regarding caching: “We use memcache as an object cache, where the object is computationally expensive to generate…”. I totally agree with this point. This is even more important when you consider the “out of the box” performance of Zend Framework; at least when compared with other frameworks or raw PHP itself. Don’t get me wrong, I love using it, but it’s not the fastest kid on the block.

So what we’re going to do is setup basic caching in readiness for the following bootstrap resource methods we’ll cover over the next two posts. Open up the default application ini file and add in, towards the top, the following:

; Cache settings
app.caching = true

; front-end options
app.cache.frontend.adapter = "Core"
app.cache.frontend.options.lifetime = 7200
app.cache.frontend.options.automatic_serialization = "true"
app.cache.frontend.options.caching = true

; back-end options
app.cache.backend.adapter = "File"
app.cache.backend.cache_dir = APPLICATION_PATH "/../data/cache/"

Following this, open the Common_Application_Bootstrap_Bootstrap.php file and add in the following code:

/`
* Setup the application cache.
*
* @return Zend_Cache
* @link http://framework.zend.com/manual/en/zend.cache.html
*/
protected function _initCache()
{
    $this->bootstrap(&'Config');
    $appConfig = Zend_Registry::get(&'config');
    $cache = NULL;

    // only attempt to init the cache if turned on
    if ($appConfig->app->caching) {
        // get the cache settings
        $config = $appConfig->app->cache;

        try {
            $cache = Zend_Cache::factory(
                $config->frontend->adapter,
                $config->backend->adapter,
                $config->frontend->options->toArray()
            );
        } catch (Zend_Cache_Exception $e) {
            // &#8230;
        }

        Zend_Registry::set(&'cache', $cache);

    }

    return $cache;
}

Following this, create the following directory structure under the application root directory:

data/

cache/

Now, you don’t have to follow this path; you can create what you want. But remember to change the path specified in:

app.cache.backend.cache_dir = APPLICATION_PATH "/../data/cache/"

What this has done is to provide a resource in the application registry called &’cache&’ that exposes a file-based cache that stores its cache files in APPLICATION_PATH “/../data/cache/”. It’s a pretty simple cache and not the fastest, but it’s a good start. You can change if you like to better suit your needs to use other Zend Cache backends, such as Memcache or APC, for example.

So, what have we done?

There’s much more to come, but we’ve now laid the foundation for a very helpful bootstrap. We’re ready to build in the future bootstrap plugin resources that we’ll be covering in the future articles; plus as many more as you can imagine or envisage. I hope you’ll be back for the next post where we’ll be covering: *routing, *databases and *navigation*.

I hope that you got a lot out of this. How would you do it, have you done it, differently? Share your thoughts either in a comment or on twitter.


You might also be interested in these tutorials too...

Wed, Nov 9, 2011

The Zend Framework Bootstrap made simple (Part 3)

Ok, we’ve established that with the Zend Framework, we need to do a bit more work than some of the other frameworks to get up to speed - but that’s not necessarily a bad thing - right?! But it can be a bit tedious and it’s something as professional developers, we want to automate away. So we’ve been addressing in this series how to do just that with a custom, extendable bootstrap class.

In the first part of the series we laid the foundation of our custom bootstrap class by creating a custom class directory structure, adding its namespace to the application ini and modifying the default application bootstrap so that it extends from it and had a look at the first component - caching.

Then, in the second part of the series, we built on the foundation laid in part one by creating plugin resources for the routing table, application navigation and the database connections - these being some of the most common tasks, usually, associated with a web-based application.

In this, the third and final part of the series, I’m going to finish up by looking at application placeholders and surprise, no not logging as originally promised, but pagination. As an added extra, we’re going to be using a key feature of Zend Application to make it a breeze.

Wed, Nov 2, 2011

The Zend Framework Bootstrap made simple (Part 2)

In the first part of the series, you’ll remember that we laid the foundation of our custom bootstrap class by creating a custom class directory structure, adding its namespace to the application ini and creating our custom bootstrap file that our application bootstrap will extend from.

After we did that, we put in the first but arguably the most important plugin resource – caching and stored it in the application registry. In this post we’re going to be building on that work and adding in three new plugin resources: routing, navigation and databases.

Tue, Nov 15, 2011

Rename uploaded files with Zend Framework

Recently I was asked how to rename a file with the Zend Framework that used a Zend Form and Zend File element. They key requirement was that it should not be a hack or a kludged solution. So I thought I’d write a quick post to provide a simple example on how it was achieved.


Want more tutorials like this?

If so, enter your email address in the field below and click subscribe.

You can unsubscribe at any time by clicking the link in the footer of the emails you'll receive. Here's my privacy policy, if you'd like to know more. I use Mailchimp to send emails. You can learn more about their privacy practices here.

Join the discussion

comments powered by Disqus