Some notes on Zend Server CE for Mac OS X

22nd June 2009

I've installed Zend Server CE on my Mac to see where it's got to and it's looking quite usable. The installation puts everything into the usr/local/zend directory which is fairly well laid out so that you can find what you are looking for. There's also a a nice admin system at http://localhost:10081 which allows you to restart PHP, view phpinfo(), configure extensions and php.ini. There's also a phpMyAdmin to help administer the bundled MySQL server.

For Mac, this is now one of the better one stop shops for easy PHP & MySQL installation.

Obviously, some things need configuration:

Set up paths

You need access to the command line zendctl.sh and mysql tools:

  • Edit ~/.bash_profile and add:
        PATH=$PATH:/usr/local/zend/bin:/usr/local/zend/mysql/bin
        LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/zend/lib
    
  • Close Terminal and restart it so that your change takes effect.

Change to port 80

The Apache in Zend Server is configured for 10088 to avoid conflicting with Apple's Web Sharing I suppose. The choice of using port 80 would have been nice as an installation option though.

To use port 80 is easy enough:

  • Stop Apache: sudo zendctl.sh stop-apache
  • Edit /usr/local/zend/apache2/conf/httpd.conf and replace Listen 10088 with Listen 80
  • Edit /usr/local/zend/apache2/bin/apachectl and change STATUSURL="http://localhost:10088/server-status" to STATUSURL="http://localhost:80/server-status"
  • If you are using vhosts, then edit /usr/local/zend/apaches/conf/httpd.conf and replace all instances 10088 with 80
  • Restart Apache:sudo zendctl.sh start-apache

Installing PHPUnit

Update PEAR first:

    sudo pear channel-update pear.php.net
    sudo pear upgrade-all

Install PHPUnit:

    sudo pear channel-discover pear.phpunit.de
    sudo pear install phpunit/PHPUnit

Installing Xdebug

  • Install Xcode so you have a compiler!
  • Stop Apache: sudo zendctl.sh stop-apache
  • Go to http://localhost:10081/ and pick the Server Setup tab. Turn off the Zend Debugger and Zend Data Cache and restart PHP
  • sudo pecl install xdebug
  • Edit /usr/local/zend/etc/php.ini and add above the [zend] section near the bottom:
    zend_extension="/usr/local/zend/lib/php_extensions/xdebug.so" 
    
    [xdebug]
    xdebug.remote_enable=1
    xdebug.remote_host="localhost"
    xdebug.remote_port=9000
    xdebug.show_local_vars=On
    xdebug.var_display_max_data=10000
    xdebug.var_display_max_depth=20
    

    (you should set up your xdebug settings as you require!)

  • Restart Apache:sudo zendctl.sh start-apache
  • The Server Setup->Extensions section of the admin interface should now show xdebug.

All in all, it's remarkably easy to set up Zend Server using PEAR and PECL is which how it should be.

The only other gotcha I noticed is that my.cnf is in /usr/local/zend/mysql/data whereas I would have thought that /usr/local/zend/etc would have been more logical.

DPC '09

15th June 2009

The Dutch PHP Conference is over and so it's time to write a short wrap-up.

Day 1

The conference was opened by a cool animated video and then Cal Evans welcomed us, with a nice short speech. The keynote was given by Andrei Zmievski of Digg. Andrei is a core devloper and gave an interesting overview of what we can expect to see next in PHP.

Cal opens DPC 09

I then listened to Paul Reinheimer talk about some problems you can encounter in conceptually easy situations. I found the section about handling account login issues very interesting and it's an area that I now intend to improve in my code. Ben Ramsey followed with a talk on the theory of REST architectures which was interesting, though not directly relevant to anything that we're doing at the moment. Making sure that I understand it when we come to make web service APIs is important though.

After lunch Matthew Weier O'Phinney talked about contributing to open source projects. Matthew gave a great talk with useful information in it. As a contributor to Zend Framework already, I mainly used this talk to learn how to evangelise the concept of contributing to other people.

I stepped out of the next session into the hallway track where I caught up with some people and then checked my email. Then Jan Lehnardt was on to talk about CouchDB. CouchDB fascinates me as it's so different from the relational databases I'm used to. I don't see that we'll be using it soon though - the paradigm shift is significant.

The day ended with the speakers dinner followed by drinking :)

Day 2

Day 2 dawned bright and far too early and I managed to leave my power adapter at the hotel, so I had to go back for it, missing the opening keynote. I got back to see most of Eli White's talk on scaling. Eli is a good speaker and the talk was well researched. I know that if I ever need to scale a website to 20 database servers and too many web servers, then I'm going to try and head hunt him...

I was intending to see Juliette Reinders Folmer's talk on UTF-8, but Paul suffered from a video adapter failure and so I lent him my laptop and stayed to watch and make sure he didn't break it. Paul gave another interesting talk whilst looking good in his suit.

After lunch, it was my turn to talk. Although I was nervous at the beginning, I think that I got into my stride and the presentation went well with intelligent questions asked by the audience. I think it helped that I advised the people who knew more than I did to leave before we started :) If you were there and haven't yet rated it, then please leave feedback!

The final breakout session that I attended was another by Ben Ramsey about HTTP. There was more here that was directly relevant to work, but I'd have preferred more on the codes side with less emphasis on the methods.

The session was closed with a conversation between Cal Evans, Ivo Jansch, Andrei Zmievski, Lorna Mitchell and Paul Reinheimer. This took the form of an interview by Cal and Ivo with their guests. It worked quite well, but I felt that the questions for Andrei and Paul were not as well structured as the ones for Lorna. There was a slide show running above their heads with Twitter and Flickr photos from the conference playing. This was very funny :)

In the evening, I went for a meal at a Pancake house that was very enjoyable and I got to see a little bit of Central Amsterdam!

Conclusion

Overall, The 2009 version of the Dutch PHP Conference was very successful. It's clear that it is being positioned to become a major conference, not just for Europe, but for the world with a significant focus on the advanced developer.

I will certainly be submitting to talk in 2010 - assuming I can think up some advanced topics to talk about!

Cheers!

Zend_Loader's autoloader deprecated in Zend Framework 1.8

30th April 2009

Zend_Loader's autoloader has been deprecated in the upcoming Zend Framework version 1.8 and so you now get a notice if you use it:

Notice: Zend_Loader::Zend_Loader::registerAutoload is deprecated as of 1.8.0 and will be removed with 2.0.0; use Zend_Loader_Autoloader instead in /www/zf-tutorial/library/Zend/Loader.php on line 207

Notice: Zend_Loader::Zend_Loader::autoload is deprecated as of 1.8.0 and will be removed with 2.0.0; use Zend_Loader_Autoloader instead in /www/zf-tutorial/library/Zend/Loader.php on line 186

Notice: Zend_Loader::Zend_Loader::autoload is deprecated as of 1.8.0 and will be removed with 2.0.0; use Zend_Loader_Autoloader instead in /www/zf-tutorial/library/Zend/Loader.php on line 186

(and so on)

This is because you have the lines:


require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();

(or similar) somewhere in your bootstrap system.

The easiest solution is to change them to:


require_once 'Zend/Loader/Autoloader.php';
$loader Zend_Loader_Autoloader::getInstance();
$loader->registerNamespace('App_');

Where 'App_' is the name of a directory on your include path that has classes within it that follow the Zend Framework naming convention, so change it as appropriate and add more if you need them.

If you need generic autoloading ability, for instance because your models directory is on your include path and you don't namespace your model classes, then add this:


$loader->setFallbackAutoloader(true);

You should also add:


$loader->suppressNotFoundWarnings(false);

when in development mode as then the new autoloader will actually tell you what the syntax error is rather than showing you a white page :)

Now you should go and read the Zend_Loader_Autoloader documentation to learn how very useful it is!

Update: You should also read Matthew's article on Zend_Loader_Autoloader as it explains this all in detail!

Shorter Link: A rev=canonical WordPress plugin

11th April 2009

Hot on the heels of my No DiggBar, I've created another extension for WordPress!

Shorter Links provides a <link> tag in the <head> section of your page with a shorter url and appropriate tags for use with the new revCanonical system. Further details can be found at laughingmeme.org, shiflett.org or benramsey.com.

The link created looks like this:

By default, the shorter url is simply {your domain}/{post id}, but the plugin also creates a custom field called "Shorter link" once a post is saved, so that you can change the shorter link to a more memorable set of characters.

Rather handily, Simon Willison, has produced a bookmarklet called Shorten so you can find out if the page you are looking at has a shorter link or not.

As an example, my Zend Framework Tutorial page has a canonical URL of http://akrabat.com/zend-framework-tutorial. I have set up a Shorter Link of http://akrabat.com/zft which will redirect to the correct page. The <link> tag for this is:
<link rev="canonical" rel="alternate shorter" href="http://akrabat.com/zft" />

Why not download Shorter Links and have a play?

Caching talk at DPC 2009

9th April 2009

The Dutch PHP Conference is being held in mid-June in Amsterdam and I'm speaking at it! My talk is called Caching for performance and in it I'll be looking at how to use caching to improve the performance of a website.

I decided to talk about this topic is that it's something that our customers have started asking about. I've started getting questions from clients asking how we can increase the speed of the their website without increasing the hosting charges. Generally, the solutions we've been looking at are to use caching at various levels to decrease the time spent creating the page. We've been interested in speeding up the response time of the site rather than worrying about scaling as most of our sites are B2B where volume of users is rarely a problem, but the time to get the page rendered is.

On the principle that a little knowledge is a dangerous thing, I thought that I'd share what we've learned. You should come along and say hi! I promise not to (over) plug my Zend Framework book!

Initial notes on Zend_Application

25th March 2009

Zend_Application is now in the incubator and being actively developed for version 1.8 of Zend Framework. I've had a little play using it with a standard ZF application with no modules and this is what I've worked out so far.

As a result this post rambles a bit; sorry about that.

Zend_Application is intended to make bootstrapping your application easier, presumably with less code. It also has a new autoloader, Zend_Loader_Autoloader, but I haven't worked out why I care about that yet.

Back to bootstrapping. The general use-case is to extend Zend_Application_Bootstrap_Base and put your code in there. There are two ways to do this bit:

  1. Add functions to your Zend_Application_Bootstrap_Base class that start with _init, for example _initConfig().
  2. Use pre-supplied (or write your own) plugin classes. The idea is that these are then easily reusable across multiple bootstrap scenarios such as testing, web service provision, standard website, etc. Presumably they are a bit slower as a result, compared to just using functions within the Zend_Application_Bootstrap_Base sub-class.

Inline initialisation functions

To use Zend_Application's bootstrap with inline functions, we need to set up an index.php that looks something like this:

//File: public/index.php
<?php

define('BASE_PATH'realpath(dirname(__FILE__) . '../'));
define('APPLICATION_PATH'BASE_PATH '/application');

set_include_path(BASE_PATH '/library/incubator'
    PATH_SEPARATOR .BASE_PATH '/library'
    PATH_SEPARATOR get_include_path()
);

// APPLICATION_ENVIROMENT defines which config section is loaded
if(!defined('APPLICATION_ENVIRONMENT')) {
    define('APPLICATION_ENVIRONMENT''development');
}

require_once 'Zend/Application.php';

$application = new Zend_Application(APPLICATION_ENVIRONMENT,
    array(
        'bootstrap'=>array('path'=>APPLICATION_PATH.'/Bootstrap.php'),
        'autoloadernamespaces' => array('Zend''App')
    ));
$application->bootstrap();
$application->run();

All we are doing here is setting some constants and the include path so that we can load the Zend Framework. As Zend_Application is in the incubator, we need that too.

We then instantiate Zend_Application passing in the environment string and an array of options. In our case, we need to tell it where to find the bootstrap class and that our library have Zend_XXX and App_XXX classes. Though, I'm not sure what it does with the autoloader info.

The Bootstrap class looks like this:

//File: application/Bootstrap.php
<?php

class Bootstrap extends Zend_Application_Bootstrap_Base
{
    protected $_config;

    function _initConfig()
    {
        // config
        $this->_config = new Zend_Config_Ini(APPLICATION_PATH 
            '/config/app.ini'APPLICATION_ENVIRONMENT);
        Zend_Registry::set('config'$this->_config);
        Zend_Registry::set('env'APPLICATION_ENVIRONMENT);

        // debugging
        if($this->_config->debug) {
            error_reporting(E_ALL E_STRICT);
            ini_set('display_errors''on');
        }
    }

    function _initDB()
    {
        // Database
        if($this->_config->db) {
            $dbAdapter Zend_Db::factory($this->_config->db);
            Zend_Db_Table_Abstract::setDefaultAdapter($dbAdapter);
            Zend_Registry::set('dbAdapter'$dbAdapter);
        }
    }

    function _initView()
    {
        // view and layout setup
        Zend_Layout::startMvc(APPLICATION_PATH '/views/layouts');
        $view Zend_Layout::getMvcInstance()->getView();
        $view->doctype('XHTML1_STRICT');
        $view->headTitle()->setSeparator(' - ');
    }

    function _initFrontController()
    {
        $frontController Zend_Controller_Front::getInstance();
        $frontController->setControllerDirectory(APPLICATION_PATH .'/controllers');
        $frontController->setParam('env'APPLICATION_ENVIRONMENT);

        // action helpers
        Zend_Controller_Action_HelperBroker::addPath(APPLICATION_PATH .'/controllers/helpers');
    }

    public function run()
    {
        $frontController Zend_Controller_Front::getInstance();
        $frontController->dispatch();
    }
}

In this case, I've grouped my init logic into four separate functions, but I could equally have created one function called _initAll(). The only function that you absolutely must have is run(), which in this case we simply dispatch the front controller. It seems a little odd that run() isn't already defined in Zend_Application_Bootstrap_Base though as it's going to be the same code for everyone.

The order of loading of the _init methods is the same order as they are defined in the class. You can change the order by calling $this->bootstrap('xxx'); in any given _init method to force _initXxx() to be run. The system is clever enough not to call the _init function twice.

Incidentally, the config file I've been using look something like this:


// File: application/config/app.ini
[site]
; All the standard site-specific settings
db.adapter PDO_MYSQL
db.params.dbname "test"
db.params.username "test"
db.params.password "test"
db.params.hostname "test"
debug 1

[productionsite]
debug 0

[staging site]

[development site]

[unittesting]
; specific config for unit testing

I've included this so you can compare it to the one used when we add the Zend_Application configuration information.

Now that we've seen how to do it with all our own code, let's repeat the entire process with Zend_Application's resource plugin system.

Using resource plugins and a config file

Another way to use Zend_Application is to use a config file to configure the bootstrapping process and point Zend_Application at it. By the way, it's not clear if the classes that we plug in to the boostrap process are called resources or plugins at the point, so I'm calling them resource plugins :)

Zend_Application comes with a number of plugins, but it's inevitable that you'll need your own. In our case, to replicate what we've done in the inline example, we're going to need a new view resource which we'll call App_Application_Resource_View as it will extend Zend_Application_Resource_View.

This resource plugin is easy to write. The system will call an init() method and you can put whatever you like there. In our case we are extending an already existing resource plugin, so we call up to the parent's init() and then do our own stuff:

// FILE: library/App/Application/Resource/View.php
<?php

class App_Application_Resource_View extends Zend_Application_Resource_View
{
    public function init()
    {
        parent::init();
        $view $this->getView();
        $view->doctype('XHTML1_STRICT');
        $view->headTitle()->setSeparator(' - ');
        Zend_Layout::startMvc(APPLICATION_PATH '/views/layouts');

    }
}

Presumably, at some point they'll be a Zend_Layout resource plugin supplied by by default, but for now, there isn't so I've started up the layout here too. It would be nice if Zend_Application_Resource_View allowed setting up the view helpers like doctype directly from the config file too.

The index.php file looks very similar to last time, except that we now tell Zend_Application about the config file:

//File: public/index.php
<?php

define('BASE_PATH'realpath(dirname(__FILE__) . '../'));
define('APPLICATION_PATH'BASE_PATH '/application');

set_include_path(BASE_PATH '/library/incubator'
    PATH_SEPARATOR .BASE_PATH '/library'
    PATH_SEPARATOR get_include_path()
);

// APPLICATION_ENVIROMENT defines which config section is loaded
if(!defined('APPLICATION_ENVIRONMENT')) {
    define('APPLICATION_ENVIRONMENT''development');
}

require_once 'Zend/Application.php';

$application = new Zend_Application(APPLICATION_ENVIRONMENT,
    APPLICATION_PATH.'/config/app.ini');
$application->bootstrap();
$application->run();

The Bootstrap class is very simple as most of the work is now done elsewhere:

//File: application/Bootstrap.php
<?php
class Bootstrap extends Zend_Application_Bootstrap_Base
{
    public function run()
    {
        Zend_Registry::set('config'$this->getOptions());
        Zend_Registry::set('env'APPLICATION_ENVIRONMENT);
        $this->frontController->dispatch();
    }
}

Note that Zend_Application doesn't store the environment string or the loaded config file to the registry and so they are unavailable to the rest of the application unless we do it ourselves. The easiest place to do it is in the run() method, but it would be nice if it did it automatically for us.

Obviously, as all our bootstrap code has disappeared, we need to tell Zend_Application what we want to do. This is done in the app.ini config file that we passed in the constructor:


//File: application/config/app.ini
[bootstrap]
; Zend_Application configuration
phpsettings.display_errors 0
phpsettings.error_reporting 8191
includepaths=
autoloadernamespaces.0 "Zend"
autoloadernamespaces.1 "App"
bootstrap.path APPLICATION_PATH"/Bootstrap_Resource.php"
pluginpaths.App_Application_Resource "App/Application/Resource"
resources.frontcontroller.controllerdirectory APPLICATION_PATH "/controllers"
resources.frontcontroller.params.0.env APPLICATION_ENVIRONMENT
resources.view =
resources.db.adapter PDO_MYSQL
resources.db.params.dbname "test"
resources.db.params.username "test"
resources.db.params.password "test"
resources.db.params.hostname "test"

[sitebootstrap]
; All the standard site-specific settings
debug 1

[productionsite]
debug 0

[staging site]

[development site]
phpsettings.display_errors 1

[unittesting]
; specific Zend_Application and other config for unit testing

Note that I'm using the PHP constants that were defined in index.php within this config file. That's part of the standard parse_ini_file() functionality, but not many people seem to take advantage of it.

Essentially, Zend_Application takes an array of options as in the second parameter of the constructor and if you don't supply one, it looks for the specific keys it uses in the config file instead. That means that in principle you don't have to use a config file, you could just pass in an array with the right information. I've not tested it though :)

The app.ini file also shows the disconnect over whether the resource plugins are called resources or plugins. We have to use the key "pluginpath" to define the directory where we store them, but use the key "resources" to configure them. It would be nice if we just called them one thing or the other. Note that we have to have a key in the resources section even if there's no parameters to set as in the case of the view resource plugin.

Note also that one phpsetting that you can't set is date.timezone as the dot is used as a separator in Zend_Config_Ini. Ideally, we'd change the separator to a "|" or something which is possible via the third parameter to Zend_Config_Ini's constructor. We can't do that though as the call to load the app.ini file is buried in Zend_Application and we can't pass any options to it. I'd guess this is by design. The easiest solution is to just call date_timezone_set() directly in your Boostrap's run() method instead.

Summary

Zend_Application has the potential to simplify the bootstrapping of an application, but, at the moment at least, you need to be aware of what it does and more importantly, what it doesn't do for you. I can't see a case where you can use it directly without either writing a few of your own _init methods or few resource plugins.

There's also the new loader which presumably will make something easier too, but that will be a separate post when I understand it and can see a use-case for it.

Finally, this should be obvious, but as the Zend_Application code is still under heavy development don't take this as gospel - by the time it is released, it could be very different!

UTF8, PHP and MySQL

18th March 2009

Everyone else probably already knows this stuff, but I hit an issue today to that took a while to sort out. Fortunately, some kind folks on IRC helped me, but as it's embarrassing to ask for help on the same issue twice, I'm writing down what I've learned!

The problem

Get a £ character stored to MySQL, retrieved and then displayed without any weird characters in front of it using UTF8.

The solution

Make sure that you are using UTF8 everywhere!

The browser:

<?php header("Content-type: text/html; charset=utf-8"); ?>

You can also use a meta tag that is redundant in theory:


<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Mysql:

Make sure that your table's collation is utf8_general_ci and that all string fields within the table also have the utf8_general_ci collation.

And here's the really important bit: make sure your client connection is also using UTF-8:

For mysql:


mysql_set_charset('utf8');

or for mysqli:


mysqli_set_charset('utf8');

or execute the SQL immediately after connection:


SET NAMES UTF8;

or for PDO:


$handle = new PDO("mysql:host=localhost;dbname=dbname",
    'username''password', 
    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

or for Zend_Db:


$params = array(
    'host' => 'localhost',
    'username' => 'username',
    'password' => 'password',
    'dbname' => 'dbname',
    'driver_options' => array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8;');
);
$db Zend_Db::factory('PDO_MYSQL'$params);

Now everything works as expected!

(as long as you don't have an output filter on your view that's too clever for its own good...)

Setting up PHP on OS X Leopard

5th March 2009

In the vein of some of Lorna's articles, this is more a note for myself than anything else. Not everything is explained in detail as it assumes you know how to use a command line...

These are the steps I take to get the Apple supplied PHP working with GD, PDO_MySQL and Xdebug working on OS X 10.5.

/usr/local

Ensure that the following directories exist:

    sudo mkdir /usr/local/include
    sudo mkdir /usr/local/bin
    sudo mkdir /usr/local/lib
    sudo mkdir -p /usr/local/man/man1

Run Apache in 32 bit mode

This saves us having to compile our own MySQL as MySQL doesn't offer a "fat" binary

  1. cd /System/Library/LaunchDaemons
  2. sudo vim org.apache.httpd.plist
  3. Immediately after the line containing <array> add:
        <string>arch</string>
        <string>-i386</string>
    
  4. Reboot

MySQL

  1. Download the 32bit version of MySQL 5.0.x for OS X 10.5 from mysql.com and install the pkg, the startup item and the pref pane.
  2. Add /usr/local/mysql/bin to the path: vim ~/.bash_profile and add:
        export PATH=~/bin:/usr/local/bin:/usr/local/sbin:/usr/local/mysql/bin:$PATH
        export EDITOR=vim
    

    at top of file. (Note that we set EDITOR whilst we are here so that svn is happy!)

  3. Set up MySQL root password:
        mysqladmin -u root password {new-password}
        mysqladmin -u root -p{new-password} -h localhost password {new-password}
        mysqladmin -u root -p reload
    

    Quit Terminal to flush the history to file. Restart Terminal and remove the history file: rm .bash_history so that {new-password} isn't in plain text on the disk.

  4. Set the correct socket information for PHP. Ensure MySQL is running via the System Preferences panel then:
        sudo mkdir /var/mysql
        sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock
    

Rest of Apache setup

  1. cd /etc/apache2
  2. sudo vim httpd.conf
  3. Find #LoadModule php5_module libexec/apache2/libphp5.so and remove the leading #
  4. Find AllowOverride None within the <Directory "/Library/WebServer/Documents">section and change toAllowOverride All so that .htaccess files will work.
  5. Restart Apache: sudo apachectl restart
  6. Open Finder and navigate to /Library/WebServer/Documents/
  7. Create a new folder called "orig" and place all files currently in the Documents folder into it.
  8. Create a new file called info.php with <?php phpinfo(); inside it.
  9. Use Safari to navigate to http://localhost/info.php and check that the PHP version is displayed (5.2.6 at the time of writing).

php.ini

  1. cd /etc
  2. sudo cp php.ini.default php.ini
  3. sudo chmod ug+w php.ini
  4. sudo chgrp admin php.ini
  5. vim php.ini (assuming your user is a member of the admin group) and change settings appropriately. Change:
        error_reporting  =  E_ALL | E_STRICT
        extension_dir = "/usr/lib/php/extensions/no-debug-non-zts-20060613"
    

    You must set the extension dir correctly. (Commenting the line out also works...)

PHP extensions

The supplied PHP doesn't come with pdo_mysql, pear or gd, so fix it.

  1. Download the correct version of PHP from http://www.php.net/releases/. (5.2.6 at time of writing)
  2. Create a directory called src in your home directory and unpack the PHP source. This creates /Users/rob/src/php-5.2.6/ in my case.

pdo_mysql

  1. cd ~/src/php-5.2.6/ext/pdo_mysql.
  2. phpize
  3. MACOSX_DEPLOYMENT_TARGET=10.5 \
    CFLAGS='-O3 -fno-common -arch i386' \
    LDFLAGS='-O3 -arch i386' \
    CXXFLAGS='-O3 -fno-common -arch i386' \
    ./configure --prefix=/usr --with-pdo-mysql=/usr/local/mysql
  4. make
  5. sudo make install
  6. Edit /etc/php.ini and find the extension_dir line and add after it:
        extension=mysql.so
  7. Restart apache: sudo apachectl restart and check in the phpinfo that pdo_mysql is now loaded.

GD

Installing GD onto the stock PHP install that is supplied with OS X is slightly more complicated than you'd expect because you need to install libjpeg first.

Libjpeg

Libjpeg is available from the Independent JPEG Group.

  1. Download the source code: http://www.ijg.org/files/jpegsrc.v6b.tar.gz
  2. extract to ~/src
  3. cd ~/src/jpeg-6b
  4. cp /usr/share/libtool/config.* .
  5. ./configure --enable-shared
  6. sudo make install
  7. Libjpeg is now installed in /usr/local/lib

GD extension

  1. cd ~/src/php-5.2.6/ext/gd
  2. phpize
  3. MACOSX_DEPLOYMENT_TARGET=10.5 \
    CFLAGS='-O3 -fno-common -arch i386' \
    LDFLAGS='-O3 -arch i386' \
    CXXFLAGS='-O3 -fno-common -arch i386' \
    ./configure --with-zlib-dir=/usr --with-jpeg-dir=/usr/local/lib --with-png-dir=/usr/X11R6 --with-freetype-dir=/usr/X11R6 --with-xpm-dir=/usr/X11R6
  4. make
  5. sudo make install
  6. Edit /etc/php.ini and find the extension_dir line and add after it:
        extension=gd.so
  7. Restart apache: sudo apachectl restart and check in the phpinfo that GD is now loaded.

PEAR

  1. cd ~/src/.
  2. curl http://pear.php.net/go-pear > go-pear.php
  3. Accept defaults, except for installation prefix (1) should be /usr/local
  4. Check that the include_path in /etc/php.ini is correct and includes the PEAR directory (/usr/local/PEAR).

Xdebug

Can't have a PHP development environment without xdebug!

  1. sudo pecl install xdebug
  2. Edit /etc/php.ini and add
        zend_extension="/usr/lib/php/extensions/no-debug-non-zts-20060613/xdebug.so"

    after the other extension lines.

  3. Restart apache: sudo apachectl restart and check in the phpinfo that xdebug is now loaded.

PHPUnit

  1. sudo pear channel-discover pear.phpunit.de
  2. sudo pear install phpunit/PHPUnit

It all works on this machines, anyway :)

Updatesee Marc Liyanage's PHP5 packages

PHP UK Conference, London

23rd February 2009

If you're going to the PHPUK conference on Friday, please say hello if you see me!

The schedule is out now, so you can plan the talks you want to see.

File uploads with Zend_Form_Element_File

29th November 2008

Now that Zend Framework 1.7 has been released, I thought I'd take a look at the built in file upload element, Zend_Form_Element_File, and see how it can be used. This is how to use it in its most basic form.

I decided to use the same set of form elements as before in order to make things easy.

Zend_Form_Element_File_Example.png

Let's start with the form:

The form

We extend Zend_Form and store it in the application/forms folder and so the class name is forms_UploadForm:

<?php

class forms_UploadForm extends Zend_Form
{
    public function __construct($options null)
    {
        parent::__construct($options);
        $this->setName('upload');
        $this->setAttrib('enctype''multipart/form-data');

        $description = new Zend_Form_Element_Text('description');
        $description->setLabel('Description')
                  ->setRequired(true)
                  ->addValidator('NotEmpty');

        $file = new Zend_Form_Element_File('file');
        $file->setLabel('File')
            ->setDestination(BASE_PATH '/data/uploads')
            ->setRequired(true);

        $submit = new Zend_Form_Element_Submit('submit');
        $submit->setLabel('Upload');

        $this->addElements(array($description$file$submit));

    }
}

As before, we set the name and enctype attribute of the form to allow for files to be uploaded. The form itself has two fields: a text field called 'description' and the file upload field called 'file', along with a submit button. Nothing especially complicated here.

The Zend_Form_Element_File element has a setDestination() method which is used to tell the underlying Zend_File_Transfer_Adapter_Http where we want the file that is uploaded to be stored. In this case we choose data/uploads.

The controller & view

The controller is also very standard:

<?php

class IndexController extends Zend_Controller_Action 
{
    public function indexAction() 
    {
        $this->view->headTitle('Home');
        $this->view->title 'Zend_Form_Element_File Example';
        $this->view->bodyCopy "<p>Please fill out this form.</p>";

        $form = new forms_UploadForm();

        if ($this->_request->isPost()) {
            $formData $this->_request->getPost();
            if ($form->isValid($formData)) {

                // success - do something with the uploaded file
                $uploadedData $form->getValues();
                $fullFilePath $form->file->getFileName();

                Zend_Debug::dump($uploadedData'$uploadedData');
                Zend_Debug::dump($fullFilePath'$fullFilePath');

                echo "done";
                exit;

            } else {
                $form->populate($formData);
            }
        }

        $this->view->form $form;

    }
}

The view, views/scripts/index.phtml, is trivial:


<h1><?= $this->title?></h1>
<?= $this->bodyCopy?>
<?= $this->form?>

If the form validates correctly, the $uploadedData array will contain the values of the form fields along with the filename of the file that was uploaded. Note that this filename is not fully qualified, so if you need the entire path to the file, then use the getFileName() method on the file element.

Conclusion

That's all there is to it for simple uploading of forms. There are still a few fairly important bugs in the component that we'll have to wait for 1.7.2 for. Specifically the Count validator doesn't always work as you'd expect and don't use getValues() and receive() as it isn't yet clever enough to know not to call move_uploaded_file() more than once.

As usual, here's a zip file of the project I created to test this: Zend_Form_Element_File_Example.zip (including Zend Framework (a snapshot of the release-1.7 branch) which is why it's 3.9MB large).