Aaron Saray

open source programmer,
web developer

entrepreneur, author
and musician

My Blog

contains PHP, Web and business/entrepreneurial related content. Please join in the conversation!

Easy Flash Messenger Messages in Zend Framework

Through reading a few blog posts over the last year and my own trial and error, I’ve developed a way of using the flashMessenger Helper in ZF that works out really well for me. (Note: if anyone knows the original blog post that I got some of the view helper from, please comment!).

Objective

  • Use FlashMessenger to store both success and failure messages and denote them as such.

Using FlashMessenger in the Controller

Now, we’re going to change the way we assign messages in the controller. Make an array of the message with a key of the type, and a value of the message. You may want to use ‘success’ and ‘failure’: in some controller…

1
$this->_helper->flashMessenger->addMessage(array('success'=>'The update was successful'));

Next, create a View Helper

Create the following view helper. I placed mine here: application/views/helpers/FlashMessages.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Zend_View_Helper_FlashMessages extends Zend_View_Helper_Abstract
{
    public function flashMessages()
    {
        $messages = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger')->getMessages();
        $output = '';
       
        if (!empty($messages)) {
            $output .= '<ul id="messages">';
            foreach ($messages as $message) {
                $output .= '<li class="' . key($message) . '">' . current($message) . '</li>';
            }
            $output .= '</ul>';
        }
       
        return $output;
    }
}

The output is initially blank. This is because we will always ‘blindly’ call this in our layout later. Then, the messages are retrieved from the flash messenger using the getStaticHelper method to retrieve the FlashMessenger helper (and call its getMessages() method). If it has content, output is appended with a UL with an ID of messages (this is for css styling later). Then, each message is looped through and added to an LI element. The ‘type’ is the class of that element, and the message is the content. (Note: since this is an array of single arrays where neither the key nor the value is known, that is the reason to use key() and current()). Finally, output is updated with the closing UL tag.

Use this in Your View

I technically put this call in my layout towards the top of my content:

1
echo $this->flashMessages();

I also modify my CSS to have styling of green for the #messages li.success and red for #messages li.failure.

Posted in zend framework | Tagged | 1 Comment

PHPUnit error: No release available for package

One of the steps to install PHPUnit is to execute the following pear commands:

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

However, after doing that, I got the following error: no release available for package pear.phpunit.de/PHPUnit – and the install failed.

I decided to execute a remote-list command – it was a thought that maybe I could see if maybe my phpunit declaration was wrong – I was just grasping at straws…

1
pear remote-list -c phpunit

This finally gave me a worthwhile error! “The value of the config option cache_dir (/tmp/pear/cache) is not a directory and attempts to creat the directory have failed”

So, I finally was successful after the following two commands:

1
2
mkdir /tmp/pear/cache
pear install phpunit/PHPUnit

Moral of the story: check to make sure PEAR has a cache directory available if you can’t install a PEAR package.

Posted in phpunit | Tagged | 2 Comments

Zend Framework View Helper for QR Codes

Google Charts has a QR code generation service (here are the details). I decided that I wanted to create my own ZF View Helper to display these on my pages. This version that I am going to show just returns the properly formatted URL for the charts API. The view must create the img tag around it.

The Code for Google QR Code

Place the following code in your view helpers location. For example… application/views/helpers/GoogleQRCode.php.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Zend_View_Helper_GoogleQRCode extends Zend_View_Helper_Abstract
{
    public function googleQRCode($data, $width = 100, $height = 100)
    {
        $url = 'https://chart.googleapis.com/chart?';
        $params = array(
                       'cht'=>'qr',
                       'chs'=>(int)$width . 'x' . (int)$height,
                       'chl'=>$data
                       );
        $url .= http_build_query($params);
        return $url;
    }
}

First thing is the function declaration. It will accept some data to encode. By default, the width and height are 100px. This can be overridden with the helper call. Next, the URL for the Google charts API is defined. Notice that this version is https – just in case its used on SSL websites. Next, the parameters to the API are built. The ‘cht’ or chart type is ‘qr’. The chart size or ‘chs’ is the integer width by the integer height. Finally, the ‘chl’ value is the data. Finally, the URL is appended with the value of the results of http_build_query() of the url parameters. Finally, the URL is returned from the method.

IMPORTANT NOTE: In the spec, it says that the data should be url encoded. The view helper is not doing that when it creates the parameter array. This is handled by http_build_query.

To use this in your view, you may have the following code: application/views/scripts/index/index.phtml

1
2
3
4
echo '<h2>Find Me Online</h2>';
echo '<img src="';
echo $this->googleQRCode('http://aaronsaray.com/contact');
echo '">';

Future options: At some point if I tend to use this more often, I might replace this entire view helper with a more model based application. The view helper will still call the model, but the model will handle retrieving and caching these QR codes. If the Google Charts API is not responding, previously generated QR codes will still be available that way!

Posted in zend framework | Tagged | 1 Comment

Mailchimp Overview Presentation: Waukesha Area Internet Marketing Meetup

I will be presenting at the WAIMM Email Marketing Software meetup today. I plan to cover the basics of Mailchimp for comparison to other services like Constant Contact.

Download the presentation powerpoint here: Mailchimp Overview Presentation

Posted in Misc Web Design | Tagged | Leave a comment

PHPUnit error with Zend_Session

Running a test, I ran into this error:

Zend_Session_Exception: Session must be started before any output has been sent to the browser; output started in /usr/share/php/PHPUnit/Util/Printer.php/173

In order to solve that, I added a line calling ob_start() to my test bootstrap file.

However, there is a better way!!

Instead, add the following line:

1
Zend_Session::$_unitTestEnabled = true;

This works flawlessly.

Posted in phpunit, zend framework | Tagged , | 3 Comments

Zend Framework: Bootstrap vs Front Controller Plugin

Today I was reviewing some old code I wrote in Zend Framework. One of the things I was doing in the Bootstrap.php file was creating an function called _initViewSettings(). In here I set a bunch of values for the xhtml version, the css files to include, etc. Now I realize my mistake:

Do not include functions in the bootstrap.php file that will never be used by command line.

Since Zend Framework projects can be launched via command line and via web page, there needs to be no overlap in the bootstrap.php file between uses. There should only be bootstrapping code – that is to say, things required in order to access or initialize global resources. The view and its settings are not a global usage object.

Instead, create a front controller plugin.

Front controller plugins are launched whenever there is a request as a webpage. They are not ran when a CLI program is ran. (Don’t get this confused with definition and initialization. The bootstrap class has to define and initialize them – it just doesn’t invoke them).

Let’s see this in practice.

Before: application/Bootstrap.php

1
2
3
4
5
6
7
8
9
10
11
12
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
  protected function _initViewSettings()
  {
    $this->bootstrap('view');
    $view = $this->getResource('view');
    $view->doctype('HTML5');
    $view->setEncoding('UTF-8');
    $view->prependStylesheet('/css/main.css');
  }
  ...
}

Now, afterward, make sure front controller plugins are defined, and then create a front controller plugin.

After: application/Bootstrap.php

1
2
3
4
5
6
7
8
9
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
  protected function _initFrontControllerPlugins()
  {
    $front = Zend_Controller_Front::getInstance();
    $front->registerPlugin(new Application_Plugin_ViewSetup());
  }
  ...
}

After: application/plugins/ViewSetup.php

1
2
3
4
5
6
7
8
9
10
11
12
class Application_Plugin_ViewSettings extends Zend_Controller_Plugin_Abstract
{
  public function routeShutdown($request)
  {
    $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
    $view = $bootstrap->bootstrap('view')->getResource('view');

    $view->doctype('HTML5');
    $view->setEncoding('UTF-8');
    $view->prependStylesheet('/css/main.css');
  }
}

Remember, always remove non-essential code from the bootstrap process.

Posted in zend framework | Tagged | 4 Comments

Theme/Template System in Zend Framework

Theme systems are very common in projects written on Drupal, Joomla, and WordPress. I didn’t see much out of the box support for themes in Zend Framework at first. However, I was wrong. It’s pretty easy. The only real decision I had to make is if I want to make themes that extend a default theme – or themes that are simple and on their own / totally encapsulated. I will do the encapsulated version – but give some pointers on how you would do the other version, too!

Make a Front Controller Plugin

Since themeing is something that is only specific to the view system that is rendered by a web page request, we’ll make a front controller plugin. I’m not creating this functionality in the bootstrap class because command line scripts don’t need to run this, only web requests (which happen to begin with the front controller).

However, we do have to register our front controller plugin using the bootstrap class. First, I’m going to register my new plugin. The plugin will be called Template. It will be located at application/plugins/Theme.php. (Note: the default ZF loader knows this location).

application/bootstrap.php

1
2
3
4
5
6
7
8
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    protected function _initFrontControllerPlugin()
    {
        $front = $this->bootstrap('frontcontroller')->getresource('frontcontroller');
        $front->registerPlugin(new Application_Plugin_Theme());
    }
}

This method simply registers a new plugin named Application_Plugin_Theme() to the front.

Pick your Theme

I’m going to create only one theme for this demonstration.

Name: My Simple Theme
Folder: simple

For the purpose of our demo, we’ll just hardcode this as the ‘chosen’ theme. You may have some sort of theme management solution.

Plan your file system

Next, I know that I’m going to have multiple view folders: one for each theme. Additionally, I’m going to have to have different folders inside of the public folder to support this.

Our initial views folder:

application/views/scripts
application/layouts
public/images

Instead, if we’re going to create assets for My Simple Theme, the folder paths will now be this:

application/views/simple/scripts
application/layouts/simple
public/themes/simple/images

Any specific content is placed in these folders instead.

Create the Front Controller Plugin

Our plugin will be called Application_Plugin_Theme. I’ll register a routeShutdown hook because this is one of the last things we have to do or figure out. Certainly don’t want to do it on every call in the loop nor do I want to do it before a redirect could occur.

application/plugins/Theme.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Application_Plugin_Theme extends Zend_Controller_Plugin_Abstract
{
  public function routeShutdown($request)
  {
    /** hard coding this for our example **/
    $theme = new stdClass;
    $theme->foldername = 'simple';
    Zend_Registry::set('theme', $theme);


    $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
    $view = $bootstrap->bootstrap('View')->getResource('View');
    $view->setBasePath(APPLICATION_PATH . '/views/' . $theme->foldername);

    $layout = $bootstrap->bootstrap('Layout')->getResrouce('Layout');
    $layout->setLayoutPath(APPLICATION_PATH . '/layouts/' . $theme->foldername);
  }
}

The first three lines of this are the theme management hardcoded portion I created. It is important later, however, in the view helper we’re going to create to have access to the $theme object — hence the Zend_Registry call.

First, access the bootstrap. Next, set the base path of the main view object by including the theme folder name in it. Notice how this is setBasePath() – if you wanted to create a system where templates inherit other ones, you may use addBasePath(). The setBasePath() resets the paths array internally and then adds the paths for /scripts and /helpers.

Next, if you are using layouts, which I’m sure you are, you basically do the same thing with the layout object.

With this plugin, now all items will load from their proper folders. Just as an example – say you are using the simple theme.

url: /blog/viewAll
controller/action: BlogController::viewAllAction()
layout: application/layouts/simple/layout.phtml
view: application/views/simple/scripts/blog/viewAll.phtml

Last step: View Helper

Since there are different public assets depending on what template that was used, we created the multiple folders in the public folder. For example, you may have public/simple/images, public/simple/js, etc.

Since this view helper is going to be shared among all of our views, however, we can put it up a level, outside of the theme root. The views folder may now look like this:

application/views/helpers
application/views/simple/helpers
application/views/simple/scripts

Create a new Helper called Application_View_Helper_Theme inside of the file: application/views/helpers/Theme.php

1
2
3
4
5
6
7
8
9
10
class Application_View_Helper_Theme
{  
  public function theme($url)
  {
    /** your theme management system may be different **/
    $theme = Zend_Registry::get('theme');
    $baseURL = "/themes/{$theme->foldername}";
    return $baseURL . $url;
  }
}

Now, modify the front controller plugin to “add” not “set” a new helper script path. Add the following code:

application/plugins/Theme.php

1
2
3
4
5
6
7
  public function routeShutdown($request)
  {
    /**SNIP**/
    $view->setBasePath(APPLICATION_PATH . '/views/' . $theme->foldername);
    /**ADD THIS BELOW HERE **/
    $view->addScriptPath(APPLICATION_PATH . '/views/scripts');
  }

Now, your zend framework project will look in the regular scripts folder as well as your theme folder for view helpers.

How might we use this?

Old view:

1
echo '<img src="/images/smiley.gif" alt="smiley">';

New view:

1
echo '<img src='" . $this->theme('/images/smiley.gif') . '" alt="smiley">';

This will render the theme URL of /themes/simple/images/smiley.gif.

Posted in zend framework | Tagged | 1 Comment

Using MySQL Bit Field as a Flag Field: Not a Good Idea

The last time I created a char(1) for a flag field, I remembered the MySQL BIT field – so I did a bit of investigation. I thought, well if I can make a bit field of one bit that is either 0/1, I can save data space in my db.

I created the table like this:

1
CREATE TABLE `test` (b BIT(1));

In order to place data in a BIT field, you must prefix it with b and have the bit value between quotes. So, I did the following test:

1
2
3
insert into test set b=b'1'
insert into test values(b'0')
select * from test

Unfortunately, when I did this, I got only ‘b’ as a response from each of those. Then I thought, maybe it needed to store ‘b’ and 1 bit was not enough to store both the identifier of ‘b’ as well as the content (mind you, one would think the identifier wouldn’t be in the data.. I’m just grasping at straws). I drop/create with a 2 bit item. Nope. Increase it to 8, still nope.

Every time I do a selection, I only get b’s. Maybe I’m doing something wrong.

1
SHOW VARIABLES LIKE "%version%";
5.1.41-3ubuntu12.6

So it should be a supported version…

Finally, I started to think – even if I got this to work, when I’m exporting data, would it have the ‘b’ in the identier field? If so, that might make it harder to create imports/exports. I really just want a 0/1, a Y/N.

If anyone can show me what I’m doing wrong, that would be awesome. For now, I’m sticking with char(1).

Posted in mysql | Tagged | 5 Comments

setTimeout proper syntax

The javascript function setTimeout can be used to execute a function after a specified amount of delay. It uses the javascript callback pattern. Its important to use the callback pattern correctly, however, or you may get different results than you expect. One example of this is the immediate execution of a function versus the callback execution. Note this example:

?View Code JAVASCRIPT
1
2
3
4
5
6
function myTime(x)
{
    alert(x);
    alert(new Date());
}
alert(new Date());

Incorrect usage:

?View Code JAVASCRIPT
1
setTimeout(myTime(), 5000);

When this is run, the script executes an alert that shows the current time. After this is dismissed, immediately the myTime() function is executed and another alert shows the current time.

The proper way to do this is to make sure the function is not called immediately, and is referenced in callback pattern:

?View Code JAVASCRIPT
1
setTimeout(myTime, 5000);

Now, the current date is immediately alerted. Five seconds later, the next date is alerted.

Last note: some have been known to enclose the function call in string notation:

?View Code JAVASCRIPT
1
setTimeout("myTime()", 5000);

This is considered to be bad form as the string must be evaluated and it is not a standard function callback pattern.

Posted in javascript | Tagged | Leave a comment

Want to come work with me? Let’s do some PHP!

Do you like to be challenged, learn new things, and have a supportive team? Well, let’s chat a bit. I’m building a team and I’m looking for great PHP developers to join it.

What would I be doing? You would be a core member of the team. I’m looking at you, Mr. I have 5+ years of experience. You’ve been there, done that, and now are looking to both share your experience with junior programmers as well as take on large projects, demonstrating your knowledge of best practices, reliability and scalability. The company is both supportive and flexible with their IT staff. Your immediate supervisor (me) and the VP of IT both support training opportunities, knowledge sharing, and sharing tips and tricks (We’re continuing to build our wiki now!). Mainly working with Zend Framework, jQuery, and HTML5/CSS3, together with the team, you will support business applications that will continue to stay with the company for years. There is plenty of work, but there is plenty of room for both personal and professional growth.

Who would I be working with? You would be working with the core web developer team. The team ranges from veteran to novice. The team also directly interfaces with the creative department to access user interface mockups, designs, and branding. A good portion of the priorities would be set by the team leader (once again, me), but always with getting your input. The industry is a print based industry moving more features onto the internet.

What are the requirements? 5+ years of Object Oriented PHP 5 experience HTML5/CSS3 experience A sense of humor jQuery/Javascript experience Knowledge of API and services including REST, SOAP, and the ability to craft custom XML. foosball skills Work with a team as well as by yourself Zend Framework experience Drupal/Joomla/Wordpress -nice to have- experience Working on-site in New Berlin (Milwaukee, Wisconsin!)

What Company? The company is Liturgical Publications Inc (LPi). Now, don’t be scared off by the name. True, almost all of the customers are church/parish based, but our team’s customer is the business itself. You do not have to have any religious views, affiliations, or experience to work here. The company has been in business for almost half a century. The main business is printing and delivering church bulletins while securing advertising revenue from print ads on the backs of them. Our team assists with moving more of this process online and automated as well as providing support for various web properties both as value-ads and stand alone salable products. Check out LPi for more.

How do I apply? Send your cover letter and resume to jobs [[at]] 4lpi.com. Mention my name and blog so it gets routed to me right away. Expect to hear from me soon!

Posted in Misc Web Design, PHP | Leave a comment