Review: Zend Framework 1.8 Web Application Development
Zend Framework is one of the most popular and hottest open-source frameworks being used today. The number of books about Web development using Zend Framework has increased over the last couple of years.
Packt Publishing sent me a copy of the book Zend Framework 1.8 Web Application Development by Keith Pope to review. I found this book to be a good introduction to the topics that a Zend Framework developer will need to know when developing enterprise Web applications. The book is also aimed at advanced users, considering there were a couple of things that I learned about this framework from reading the book. The book not only shows you how the Zend Framework works, but also how to write an application for real-world usage. The book covers access control, performance optimization, testing, debugging and application design. The writing is clear, the code examples are good and Keith does an excellent job of walking you through the life-cycle of a request, explaining how things work and how you can extend the framework to fit your needs.
Here’s an example of the Storefront application:
http://code.google.com/p/zendframeworkstorefront/source/browse
Conclusion
The book is very well-written, nicely structured and full of highly practical advice. Overall, I’m happy to say that Zend Framework 1.8 Web Application Development fulfilled my expectations.
Other Reviews
“The content of the book is delivered in a fluent, very enthusiastic and ‘knowledge-pillowed’ writing tone. By implementing or working through the Storefront application seasoned web developers using older versions of the Framework will get a good blue sheet on new components like Zend_Application and it’s implication in the bootstrapping process; while new developers tending towards picking up the Zend Framework will get a current and well compiled guide, which might first start off with a steep learning-curve but will turn into profund knowledge once hanging in there.”
“The flow of this book is heavily inspired by the famous Ruby on Rails book, Agile Web Development with Rails, where the author invites you to join the process of building a demo application, which in both cases is a shopping cart system. Judging by the feedback of the Rails book, most people feel quite comfortable learning a framework this way, some don’t. I guess if you are not a fan of following a defined learning structure, this book probably isn’t for you.”
Sky Named Britain’s Most Admired Company
Based on a survey of thousands of managers and investment analysts, Management Today has named BSkyB as Britain’s Most Admired Company for 2009. BSkyB is the youngest company ever to win this Award.
BSkyB beat off the superstore giant Tesco into second place. Johnson Mathey took the third slot, with Cadbury, GlaxoSmithKline and Rolls-Royce trailing at numbers four, five and six.
BSkyB headed off the sector in all of the criteria laid down by the organizers, coming out top in “quality of goods and services”, “quality of marketing” and “capacity to innovate”.
Most Admired Top 20, 2009
(Last year’s position in brackets)
1 (4) BSkyB 72.25 2 (5) Tesco 71.38 3 (2) Johnson Matthey 71.00 4 (18) Cadbury 70.40 5 (19) GlaxoSmithKline 70.00 6 (7) Rolls-Royce 69.96 7 (26) BP 67.08 8 (11) BG Group 67.03 9 (1) Diageo 65.83 10 (47) Cobham 65.75 11 (3) Unilever 65.0 12 (52) BAE Systems 64.9 13 (51) Ultra Electronics 64.7 14 (154) Centrica 64.4 14 (24) Royal Dutch Shell 64.4 16 (81) Admiral 63.9 16 (17) Capita Group 63.9 18 (27) Sainsbury 63.8 19 (55) Balfour Beatty 63.1 20 (29) Marks & Spencer 62.9
BSkyB is a great company to work for, filled with talented people. Congratulation for this prestigious award!
Links
Command-line memcached stat reporter
Nicholas Tang wrote a nice little perl script that shows a basic memcached top display for a list of servers. You can specify thresholds, for instance, and it’ll change color to red if you exceed the thresholds. You can also choose the refresh/sleep time, and whether to show immediate (per second) stats, or lifetime stats.
To install it you only need to download the script and make it executable:
$ curl http://memcache-top.googlecode.com/files/memcache-top-v0.6 > ~/bin/memcache-top $ chmod +x ~/bin/memcache-top $ memcache-top --sleep 3 --instances 10.50.11.3,10.50.11.4,10.50.11.5
Here’s some sample output:
memcache-top v0.6 (default port: 11211, color: on, refresh: 3 seconds) INSTANCE USAGE HIT % CONN TIME EVICT/s GETS/s READ/s WRITE/s 10.50.11.3:11211 88.9% 69.7% 1661 0.9ms 0.3 47 13.9K 9.8K 10.50.11.4:11211 88.8% 69.9% 2121 0.7ms 1.3 168 17.6K 68.9K 10.50.11.5:11211 88.9% 69.4% 1527 0.7ms 1.7 48 14.4K 13.6K AVERAGE: 84.7% 72.9% 1704 1.0ms 1.3 69 13.5K 30.3K TOTAL: 19.9GB/ 23.4GB 20.0K 11.7ms 15.3 826 162.6K 363.6K (ctrl-c to quit.)
Project Home
http://code.google.com/p/memcache-top/
Managing Multiple Build Environments
One of the challenges of Web development is managing multiple build environments. Most applications pass through several environments before they are released. These environments include: A local development environment, a shared development environment, a system integration environment, a user acceptance environment and a production environment.
Automated Builds
Automated builds provide a consistent method for building applications and are used to give other developers feedback about whether the code was successfully integrated or not. There are different types of builds: Continuous builds, Integration builds, Release builds and Patch builds.
A source control system is the main point of integration for source code. When your team works on separate parts of the code base, you have to ensure that your checked in code doesn’t break the Integration build. That’s why it is important that you run your unit tests locally before checking in code.
Here is a recommended process for checking code into source control:
- Get the latest code from source control before running your tests
- Verify that your local build is building and passing all the unit tests before checking in code
- Use hooks to run a build after a transaction has been committed
- If the Integration build fails, fix the issue because you are now blocking other developers from integrating their code
Hudson can help you automate these tasks. It’s extremely easy to install and can be configured entirely from a Web UI. Also, it can be extended via plug-ins and can execute Phing, Ant, Gant, NAnt and Maven build scripts.
Build File
We need to create a master build file that contains the actions we want to perform. This script should make it possible to build the entire project with a single command line.
First we need to separate the source from the generated files, so our source files will be in the “src” directory and all the generated files in the “build” directory. By default Ant uses build.xml as the name for a build file, this file is usually located in the project root directory.
Then, you have to define whatever environments you want:
project/
build/
files/
local/
development/
integration/
production/
packages/
development/
project-dev-0.1RC-1.noarch.rpm
integration/
production/
src/
tests/
build.xml
Build files tend to contain the same actions:
- Delete the previous build directory
- Copy files
- Manage dependencies
- Run unit tests
- Generate HTML and XML reports
- Package files
The target element is used as a wrapper for a sequences of actions. A target has a name, so that it can be referenced from elsewhere, either externally from the command line or internally via the “depends” or “antcall” keyword. Here’s a basic build.xml example:
<?xml version="1.0" encoding="iso-8859-1"?>
<project name="project" basedir="." default="main">
<property environment="env"/>
<property name="src.dir" value="src"/>
<property name="tests.dir" value="tests"/>
<property name="build.dir" value="build"/>
<property name="build.env" value="local"/>
<target name="init"></target>
<target name="test"></target>
<target name="clean"></target>
<target name="build" depends="test, clean"></target>
<target name="package-rpm"></target>
<target name="deploy"></target>
<target name="profile"></target>
<target name="test-selenium"></target>
<target name="build-development" depends="init"></target>
<target name="build-integration" depends="init"></target>
<target name="build-production" depends="init"></target>
</project>
The property element allows the declaration of properties which are like user-definable variables available for use within an Ant build file. The following example intends to describe a typical Ant build file, of course, it can be easily modified to suit your personal needs.
<?xml version="1.0" encoding="iso-8859-1"?>
<project name="project" basedir="." default="main">
<property environment="env"/>
<property name="src.dir" value="src"/>
<property name="tests.dir" value="tests"/>
<property name="build.dir" value="build"/>
<property name="build.env" value="local"/>
<target name="init">
<echo message="Hudson build ID: ${env.BUILD_ID}"/>
<echo message="Hudson build number: ${env.BUILD_NUMBER}"/>
<echo message="SVN revision: ${env.SVN_REVISION}"/>
<tstamp>
<format property="build.datetime" pattern="dd-MMM-yy HH:mm:ss"/>
</tstamp>
<echo message="Build started at ${build.datetime}"/>
</target>
<target name="test">
...
</target>
<target name="clean">
<delete dir="${build.dir}/files/${build.env}"/>
<delete dir="${build.dir}/packages/${build.env}"/>
<mkdir dir="${build.dir}/files/${build.env}"/>
<mkdir dir="${build.dir}/packages/${build.env}"/>
</target>
<target name="build" depends="test, clean">
<echo message="Environment: ${build.env}"/>
...
</target>
...
<target name="build-development" depends="init">
<property name="build.env" value="development"/>
<antcall target="build"/>
<antcall target="package-rpm"/>
<antcall target="deploy"/>
<antcall target="profile"/>
</target>
<target name="build-integration" depends="init">
<property name="build.env" value="integration"/>
<antcall target="build"/>
<antcall target="package-rpm"/>
<antcall target="deploy"/>
<antcall target="test-selenium"/>
</target>
<target name="build-production" depends="init">
...
</target>
</project>
Properties can be defined either inside the buildfile or in a standalone properties file. For example:
<?xml version="1.0" encoding="iso-8859-1"?>
<project name="project" basedir="." default="main">
<property environment="env"/>
<property file="local.properties"/>
...
<target name="build" depends="test, clean">
<echo message="Environment: ${build.env}"/>
...
</target>
<target name="build-development" depends="init">
<property file="development.properties"/>
<antcall target="build"/>
...
</target>
<target name="build-integration" depends="init">
<property file="integration.properties"/>
<echo message="Environment: ${build.env}"/>
...
</target>
</project>
There are different ways to target multiple environments. I hope I have covered enough of the basic functionality to get you started. Good luck.
Testing Zend Framework Action Controllers With Mocks
In this post I’ll demonstrate a unit test technique for testing Zend Framework Action Controllers using Mock Objects. Unit testing controllers independently has a number of advantages:
- You can develop controllers test-first (TDD).
- It allows you to develop and test all of your controller code before developing any of the view scripts.
- It helps you quickly identify problems in the controller, rather than problems in one of the combination of Model, View and Controller.
The Action Controller I’m going to test has only one method, profileAction():
tests/application/controllers/UserController.php
class UserController extends Zend_Controller_Action
{
public function profileAction()
{
$this->view->userId = $this->_getParam('user_id');
return $this->render();
}
}
tests/application/ControllerTestCase.php
class ControllerTestCase extends Zend_Test_PHPUnit_ControllerTestCase
{
public $application;
public function setUp()
{
$this->application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/config/application.ini'
);
$this->bootstrap = array($this, 'bootstrap');
parent::setUp();
}
public function tearDown()
{
Zend_Controller_Front::getInstance()->resetInstance();
$this->resetRequest();
$this->resetResponse();
$this->request->setPost(array());
$this->request->setQuery(array());
}
public function bootstrap()
{
$this->application->bootstrap();
}
}
tests/application/controllers/UserControllerTest.php
require_once TESTS_PATH . '/application/ControllerTestCase.php';
require_once APPLICATION_PATH . '/controllers/UserController.php';
class UserControllerTest extends ControllerTestCase
{
public function testStubRenderMethodCall()
{
$request = $this->getRequest()
->setRequestUri('/user/profile/1')
->setParams(array('user_id'=>1))
->setPathInfo(null);
$response = $this->getResponse();
$this->getFrontController()
->setRequest($request)
->setResponse($response)
->throwExceptions(true)
->returnResponse(false);
$controller = $this->getMock(
'UserController',
array('render'),
array($request, $response, $request->getParams())
);
$controller->expects($this->once())
->method('render')
->will($this->returnValue(true));
$this->assertTrue($controller->profileAction());
$this->assertTrue($controller->view->user_id == 1);
}
}
You can go further making both the tests and the implementation more sophisticated. The main point is that you can build and test a controller in a way that doesn’t require a view script to be written to do so.
Zend Framework Known Issues
By default Zend_Test_PHPUnit_ControllerTestCase sets the redirector exit value to false, leading to unexpected behavior when unit testing your code. For that reason, make sure you always add a return statement after calling a utility method:
class UserController extends Zend_Controller_Action
{
public function profileAction()
{
if (null == $this->_getParam('user_id', null) {
return $this->_redirect('/');
}
return $this->render();
}
}
If you want the Front Controller to throw exceptions, you have no other choice than to overwrite the dispatch method and pass a boolean TRUE to the throwExceptions() method:
class ControllerTestCase extends Zend_Test_PHPUnit_ControllerTestCase
{
...
public function dispatch($url = null)
{
// redirector should not exit
$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$redirector->setExit(false);
// json helper should not exit
$json = Zend_Controller_Action_HelperBroker::getStaticHelper('json');
$json->suppressExit = true;
$request = $this->getRequest();
if (null !== $url) {
$request->setRequestUri($url);
}
$request->setPathInfo(null);
$this->getFrontController()
->setRequest($request)
->setResponse($this->getResponse())
->throwExceptions(true)
->returnResponse(false);
$this->getFrontController()->dispatch();
}
...
}
The Dispatcher not only violates the DRY principle but also suffers from amnesia. The problem is that it doesn’t store the instance of the Action Controller, instead, it destroys it (Zend_Controller_Dispatcher_Standard Line 305). You can easily get around this issue by extending the standard dispatcher and overwriting the dispatch() method:
class Zf_Controller_Dispatcher_Standard extends Zend_Controller_Dispatcher_Standard
{
...
public function dispatch($url = null)
{
...
Zend_Registry::set('Zend_Controller_Action', $controller);
// Destroy the page controller instance and reflection objects
$controller = null;
}
This will allow you to access the view object after dispatching the request:
class ExampleControllerTest extends ControllerTestCase
{
public function testDefaultActionRendersViewObject()
{
$this->dispatch('/');
$controller = Zend_Registry::get('Zend_Controller_Action');
$this->assertEquals('ExampleController', get_class($controller));
$this->assertTrue(isset($controller->view));
}
Links
PHPUnit: Testing Zend Framework Controllers
PHPUnit: Mock Objects
Symfony 1.3 Web Application Development
Packt Publishing recently sent me a copy of the book “Symfony 1.3 Web Application Development” to review.
This book is not a reference guide, but an example driven tutorial that takes you through the process of building Model-View-Controller-based web applications. You will learn how to create and develop a simple online store application. It also covers best practices for better and quicker application development.
The book is based on the latest version of the Symfony Framework, and does a great job telling you what you get out of the box and how it works, which is perfect for hitting the ground running. During the development you are introduced to the concepts and features of the MVC framework. However, for those who want to know more about the framework, the book doesn’t explain how things work under the covers. This book is more for beginners who want to get started with Symfony 1.3.
One thing I didn’t like about this book is that it uses Propel instead of Doctrine as the default ORM framework. Apart from that, it does a great job explaining and demonstrating with practical examples how to build a Web application from scratch.
Overall, and considering that some of the topics in this book have already been covered in Practical Symfony 1.3, I rate this book 4 out of 5.
Database Replication Adapter for Zend Framework Applications
Database replication is an option that allows the content of one database to be replicated to another database or databases, providing a mechanism to scale out the database. Scaling out the database allows more activities to be processed and more users to access the database by running multiple copies of the databases on different machines.
The problem with monolithic database designs is that they don’t establish an infrastructure that allows for rapid changes in business requirements. Here is where database replication comes into play. Replication can be used effectively for many different purposes, such as separating data entry and reporting, distributing load across servers, providing high availability, etc.
In 2008, Paul M. Jones announced the release of an SQL adapter that allows Solar users to connect to master/slave database installations. My first reaction was: Great! This will inspire other FOSS developers to create similar components. And guess what, it did. I wrote my own ReplicationAdapter. It’s not great, but it’s flexible enough to support the most commonly used replication scenarios:
Single-Master Replication
In the simplest replication scenario, the master copy of directory data is held in a single read-write replica on one server called the supplier server. The supplier server also maintains changelog for this replica. On another server, called the consumer server, there can be multiple read-only replicas.
Configuration array:
$db = array(
'adapter' => 'Pdo_Mysql',
'driver_options' => array(PDO::ATTR_TIMEOUT=>5),
'username' => 'root',
'password' => 'root',
'dbname' => 'test',
'master_servers' => 1,
'servers' => array(
array('host' => 'db.master-1.com'),
array('host' => 'db.slave-1.com'),
array('host' => 'db.slave-2.com')
)
);
// or ...
$db = array(
'adapter' => 'Pdo_Mysql',
'driver_options' => array(PDO::ATTR_TIMEOUT=>5),
'dbname' => 'test',
'master_servers' => 1,
'servers' => array(
array('host' => 'db.master-1.com', 'username' => 'user1', 'password'=>'pass1'),
array('host' => 'db.slave-1.com', 'username' => 'user2', 'password' => 'pass2'),
array('host' => 'db.slave-2.com', 'username' => 'user3', 'password' => 'pass3')
)
);
Zend_Registry::set('db_config_array', $db);
In the setup above, all writes will go to the master connection and all reads will be randomly distributed across the available slaves.
Multi-Master Replication
This type of configuration can work with any number of consumer servers. Each consumer server holds a read-only replica. The consumers can receive updates from all the suppliers. The consumers also have referrals defined for all the suppliers to forward any update requests that the consumers receive.
$db = array(
'adapter' => 'Pdo_Mysql',
'driver_options' => array(PDO::ATTR_TIMEOUT=>5),
'username' => 'root',
'password' => 'root',
'dbname' => 'test',
'master_servers' => 2,
'master_read' => true,
'servers' => array(
array('host' => 'db.master-1.com'),
array('host' => 'db.master-2.com')
)
);
Zend_Registry::set('db_config_array', $db);
Using a distributed memory caching system
Database connections are expensive and it’s very inefficient for an application to try to connect to a server that is down or not responding. A distributed memory caching system can help alleviate this problem by keeping a list of all the failed connections in memory, sharing that information across multiple servers and allowing the application to access it before attempting to open a connection.
To enable this option, you have to register an instance of the Memcached adapter class:
Zend_Registry::set('db_config_array', $db);
...
$cache = Zend_Cache::factory('Core', 'Zend_Cache_Backend_Memcached', $f, $b);
Zend_Registry::set('Zend_Cache', $cache);
Zend Framework Example
Here is a short and simple example of how the ReplicationAdapter might be used in a ZF application:
class SingleMasterDb extends Zf_Db_ReplicationAdapter
{
public function fecthAll()
{
$db = $this->getConnection('slave');
$query = $db->select()->from('test');
return $db->fetchAll($query);
}
public function insert($data)
{
$db = $this->getConnection('master');
$db->insert('test', $data);
return $db->lastInsertId();
}
public function update($id, $data)
{
$db = $this->getConnection('master');
$where = $db->quoteInto('id = ?', $id);
return $db->update('test', $data, $where);
}
}
Source Code:
http://fedecarg.com/repositories/show/zfreplicationadapter
Adding theme support to your Zend Framework application
This is a brief explanation on how to add theme support to your Zend Framework application and how to ensure those themes are self-contained, easy to distribute and install.
Themes are very powerful and extremely easy to develop. They allow you to quickly switch between layouts and change the look and feel of your application. You can use themes to show, for example, a mobile friendly version of your site.
Making a Zend Framework application theme-able is a three-step process.
First, modify your directory structure:
application/
controllers/
library/
public/
themes/
default/
css/
images/
templates/
custom/
css/
images/
templates/
Then, edit your Bootstrap class:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initView()
{
$theme = 'default';
if (isset($this->config->app->theme)) {
$theme = $this->config->app->theme;
}
$path = PUBLIC_PATH.'/themes/'.$theme.'/templates';
$layout = Zend_Layout::startMvc()
->setLayout('layout')
->setLayoutPath($path)
->setContentKey('content');
$view = new Zend_View();
$view->setBasePath($path);
$view->setScriptPath($baseDir);
return $view;
}
}
And finally, copy your view scripts and layouts to the templates directory:
application/
library/
public/
themes/
full-site/
css/
images/
templates/
error/
index/
partials/
layout.phtml
mobile-site/
css/
images/
templates/
Voila, mission accomplished.
Zend Framework DAL: DAOs and DataMappers
A Data Access Layer (DAL) is the layer of your application that provides simplified access to data stored in persistent storage of some kind. For example, the DAL might return a reference to an object complete with its attributes instead of a row of fields from a database table.
A Data Access Objects (DAO) is used to abstract and encapsulate all access to the data source. The DAO manages the connection with the data source to obtain and store data. Also, it implements the access mechanism required to work with the data source. The data source could be a persistent store like a database, a file or a Web service.
And finally, a DataMapper is used to move data between the object and a database while keeping them independent of each other. The DataMapper main responsibility is to transfer data between the two and also to isolate them from each other.
Zend Framework Example
app/
controllers/
UserController.php
views/
lib/
Project/
Dao/
Db/
User.php
Service/
User.php
DataMapper/
User.php
Entity/
User.php
Model/
User.php
Zf/
DataSource/
Dao/
Mapper.php
Domain/
Entity.php
Db/
Adapter.php
Database Table Structure
CREATE TABLE `user` ( `id` int(11) NOT NULL auto_increment, `first_name` varchar(100) NOT NULL, `last_name` varchar(100) NOT NULL, PRIMARY KEY (`id`) )
The User DAO
The DAO pattern provides a simple, consistent API for data access that does not require knowledge of an ORM interface. DAO does not just apply to simple mappings of one object to one relational table, but also allows complex queries to be performed and allows for stored procedures and database views to be mapped into data structures.
A typical DAO design pattern interface is shown below:
class Project_Dao_Db_User extends Zf_Db_Adapter
{
public function find($id)
{
$db = $this->getConnection();
$query = $db->select()->from('user')->where('id = ?', $id);
return $db->fetchRow($query);
}
public function findAll()
{
$db = $this->getConnection();
$query = $db->select()->from('user');
return $db->fetchAll($query);
}
public function insert($data)
{
$db = $this->getConnection();
$db->insert('user', $data);
return $db->lastInsertId();
}
public function update($id, $data)
{
$db = $this->getConnection();
$where = $db->quoteInto('id = ?', $id);
return $db->update('user', $data, $where);
}
public function delete($id)
{
$db = $this->getConnection();
$where = $db->quoteInto('id = ?', $id);
return $db->delete('user', $where);
}
}
Source Code: Zf_Db_Adapter
The User Entity
An Entity is anything that has continuity through a life cycle and distinctions independent of attributes that are important to the application’s user.
class Project_Entity_User extends Zf_Domain_Entity
{
public $id;
public $firstName;
public $lastName;
}
Source Code: Zf_Domain_Entity
The User DataMapper
class Project_DataMapper_User extends Zf_DataSource_Dao_Mapper
{
protected $_map = array(
'id' => 'id',
'first_name' => 'firstName',
'last_name' => 'lastName'
);
public function find($id)
{
$dao = new Project_Dao_Db_User();
$row = $dao->find($id);
if (!$row) {
return false;
}
return $this->map($row);
}
}
Source Code: Zf_DataSource_Dao_Mapper
The User Model
The following class represents the User Relational Model:
class Project_Model_User
{
public function getUser($id)
{
$mapper = new Project_DataMapper_User();
$mapper->setEntity(new Project_Entity_User());
$user = $mapper->find($id);
return $user;
}
}
The User Controller
class UserController extends Zend_Controller_Action
{
public function viewAction()
{
$model = new Project_Model_User();
$user = $model->getUser($this->_getParam('id'));
if ($user) {
$userId = $user->getId();
$userFirstName = $user->getFirstName();
$userLastName = $user->getLastName();
// get an array of database fields and values
$row = $user->getRow();
}
}
}
Keep in mind that ORM tools such as phpDataMapper and Doctrine offer an alternative way of modeling data. ORMs and ERMs are popular with Web frameworks, and the combination of an ORM and DDD makes DAOs redundant, however, it has not been proven to be better than a straightforward approach of implementing a collection of domain-specific data access functions.
That’s all, I hope you’ve found this post useful.
Increase speed and reduce bandwidth usage with ZF and Apache
Apache’s mod_deflate module provides the DEFLATE output filter that allows output from your server to be compressed before being sent to the client over the network.
There are two ways of enabling gzip compression:
- Using Apache’s mod_deflate
- Using PHP’s built-in functions
Encoding the output and setting the appropriate headers manually makes the code more portable. Keep in mind that there are hundreds of Linux distributions, each slightly different to significantly different. To allow portability the application should not make assumptions about the OS or config involved.
Using Apache
1. Enable mod_deflate
Debian/Ubuntu:
$ a2enmod deflate $ /etc/init.d/apache2 force-reload
2. Configure mode_deflate
$ nano /etc/apache2/mods-enabled/deflate.conf # # mod_deflate configuration # <IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/xml AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/x-javascript DeflateCompressionLevel 9 BrowserMatch ^Mozilla/4 gzip-only-text/html BrowserMatch ^Mozilla/4\.0[678] no-gzip BrowserMatch \bMSIE !no-gzip !gzip-only-text/html DeflateFilterNote Input instream DeflateFilterNote Output outstream DeflateFilterNote Ratio ratio </IfModule>
Using PHP
Create a gzip compressed string in your bootstrap file:
try {
$frontController = Zend_Controller_Front::getInstance();
if (@strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
ob_start();
$frontController->dispatch();
$output = gzencode(ob_get_contents(), 9);
ob_end_clean();
header('Content-Encoding: gzip');
echo $output;
} else {
$frontController->dispatch();
}
} catch (Exeption $e) {
if (Zend_Registry::isRegistered('Zend_Log')) {
Zend_Registry::get('Zend_Log')->err($e->getMessage());
}
$message = $e->getMessage() . "\n\n" . $e->getTraceAsString();
/* trigger event */
}