Posts tagged: zend

Zend Framework Body Tag View Helper

By Steven Lloyd Watkin, Saturday 21st August 2010 11:13 pm
Photo from  http://www.flickr.com/photos/daniello/

Photo from http://www.flickr.com/photos/daniello/

Summary

Here I discuss the creation of a view helper for modifying HTML tags, and more specifically body tags. The created view helper allows functionality similar to the head*/inlineScript view helpers already in the standard Zend Framework view helpers, but allows the programmatic modification of tag attributes. Definitely check out the demo page and the code on github.

Motivation

The standard Zend Framework view helpers are a great set of tools for streamlining mundane view tasks and allowing for the modification/addition of scripts and header blocks (generally held in the layout) from within the view without applying ugly hacks (i.e. the head*/inlineScript view helpers).

Upon occasion I have found need to make modifications to the <body> tag, for example adding an onload, class, or style attribute etc. I also required to be able to perform this from within other view helpers. Take this following contrived example…

On website X, certain pages include standard dojo forms. These dojo forms are held within view helpers for convenience. Generally it has been decided not to include the dojo CSS classes in the body tag and only add them when necessary. There maybe several view helpers on the page that need to add their own attributes to the body tag. (I said it was contrived)

The code is available in my GIT repository @ github and the demo page.
Continue reading 'Zend Framework Body Tag View Helper'»

Post to Twitter Tweet This Post Post to Plurk Plurk This Post Post to Yahoo Buzz Buzz This Post Post to Delicious Delicious Post to Digg Digg This Post Post to Facebook Facebook Post to MySpace MySpace Post to Ping.fm Ping This Post Post to Reddit Reddit Post to StumbleUpon Stumble This Post

Quick Start Symfony DI (Dependency Injection) Tutorial

By Steven Lloyd Watkin, Saturday 14th August 2010 2:21 pm

What is Dependency Injection (DI)?

Dependency injection is a technique that allows for loosely coupled objects within a software application. Generally if an object requires access to the functionality of another it would be instantiated internally leading to tightly coupled systems. By implementing dependency injection we inject the required objects ready for use (sometimes also referred to inversion of control – IOC). Take the following example:

<?php
class DecisionMaker {
    public function makeDecision(array $parameters) {
        // Need the database adapter
        $dp = new DecisionParameters();
        $parameterScore = $dp->getScore($parameters);
        /* ... Some more decision logic ... */
        return ($parameterScore > 50);
    }
}

This piece of code is said to be tightly coupled to the DecisionParameters object. Rewriting the above in a loosely coupled fashion we’d have something like….

<?php
class DecisionMaker {
    private $_dp;
    public function __construct($dp) {
        $this->_dp = $dp;
    }
    public function makeDecision(array $parameters) {
        $parameterScore = $this->_dp->getScore($parameters);
        /* ... Some more decision logic ... */
        return ($parameterScore > 50);
    }
}

Whilst gaining the benefits of loosely coupled code we are adding complexity such that each time an object is instantiated we also have to instantiate its dependencies and pass these in too. For example, this:

$choice = new DecisionMaker();
echo $choice->makeDecision(array('effort' => 'low', 'return' => 'high'));

now becomes:

$dp = new DecisionParameters();
$choice = new DecisionMaker($dp);
echo $choice->makeDecision(array('effort' => 'low', 'return' => 'high'));

This situation becomes more painful as the number of dependencies for a class is increased, and what if the dependencies themselves have dependencies? This can quite quickly become an object administration nightmare! Enter dependency injection containers (or frameworks)…
Continue reading 'Quick Start Symfony DI (Dependency Injection) Tutorial'»

Post to Twitter Tweet This Post Post to Plurk Plurk This Post Post to Yahoo Buzz Buzz This Post Post to Delicious Delicious Post to Digg Digg This Post Post to Facebook Facebook Post to MySpace MySpace Post to Ping.fm Ping This Post Post to Reddit Reddit Post to StumbleUpon Stumble This Post

Naked Zend_Layout and Zend_View

By Steven Lloyd Watkin, Tuesday 10th August 2010 11:47 pm

In this article I look at using Zend_Layout and Zend_View along with a simple front controller to show how it is possible to start separating business logic and presentation within your application. All code is available on github:
Naked Zend_Layout and Zend_View on GitHub.

Continue reading 'Naked Zend_Layout and Zend_View'»

Post to Twitter Tweet This Post Post to Plurk Plurk This Post Post to Yahoo Buzz Buzz This Post Post to Delicious Delicious Post to Digg Digg This Post Post to Facebook Facebook Post to MySpace MySpace Post to Ping.fm Ping This Post Post to Reddit Reddit Post to StumbleUpon Stumble This Post

Zend Framework Per Module Layout Settings – Follow Up

By Steven Lloyd Watkin, Tuesday 16th February 2010 8:48 pm

As a follow up to my previous post on per module based layout settings for Zend Framework, I’ve updated the code to require less configuration then before (not that it required more that a few lines in your application configuration!).
Continue reading 'Zend Framework Per Module Layout Settings – Follow Up'»

Post to Twitter Tweet This Post Post to Plurk Plurk This Post Post to Yahoo Buzz Buzz This Post Post to Delicious Delicious Post to Digg Digg This Post Post to Facebook Facebook Post to MySpace MySpace Post to Ping.fm Ping This Post Post to Reddit Reddit Post to StumbleUpon Stumble This Post

Creating URL in Zend Customer View Helper

By Steven Lloyd Watkin, Thursday 28th January 2010 11:01 pm

This may seem simple, but I was banging my head trying to create a URL in a custom view helper in Zend Framework. I have routing setup which gets the module from the sub-domain in use so I couldn’t use a simple hardcoded URL.

Continue reading 'Creating URL in Zend Customer View Helper'»

Post to Twitter Tweet This Post Post to Plurk Plurk This Post Post to Yahoo Buzz Buzz This Post Post to Delicious Delicious Post to Digg Digg This Post Post to Facebook Facebook Post to MySpace MySpace Post to Ping.fm Ping This Post Post to Reddit Reddit Post to StumbleUpon Stumble This Post

Dynamically add pages to Zend_Navigation container at runtime

By Steven Lloyd Watkin, Thursday 7th January 2010 10:50 pm

In a continuation on my last post about Zend_Navigation, Route requests for sitemap.xml to custom controller/action, this post is about dymnamically adding pages to a Zend_Navigation container at runtime/script execution.

Its all well and good specifying your pages in a ini or xml file but at some point you’re going to have changing pages in your site that you want as part of a menu, sitemap, or to be included in your breadcrumb trail. Therefore what we need to do is add pages to our Zend_Navigation container at runtime. Examples for this would be in adding news items, blog posts, or page comments, etc.

Continue reading 'Dynamically add pages to Zend_Navigation container at runtime'»

Post to Twitter Tweet This Post Post to Plurk Plurk This Post Post to Yahoo Buzz Buzz This Post Post to Delicious Delicious Post to Digg Digg This Post Post to Facebook Facebook Post to MySpace MySpace Post to Ping.fm Ping This Post Post to Reddit Reddit Post to StumbleUpon Stumble This Post

Route requests for sitemap.xml to custom controller/action

By Steven Lloyd Watkin, Wednesday 6th January 2010 12:13 am

In order to direct requests for /sitemap.xml to a custom controller and action in your Zend Framework application simply add the following in your application.ini or alternative config file (e.g. I use navigation.ini):

resources.router.routes.sitemap.route                = "sitemap.xml"
resources.router.routes.sitemap.defaults.controller  = index
resources.router.routes.sitemap.defaults.action      = sitemap

Example code for outputting can be seen by creating an action in the appropriate controller (e.g. my sitemap lies in the index controller, sitemap action):

<php
class IndexController
    extends Zend_Controller_Action
{
    /**
     * Renders a sitemap based on Zend_Navigation setup
     */
    public function sitemapAction()
    {
    	echo $this->view->navigation()->sitemap();
    	$this->view->layout()->disableLayout();
    	$this->_helper->viewRenderer->setNoRender(true);
    }
}

Sitemaps can quickly and easily be generated using Zend_Navigation, a great quick tutorial (and generally very useful for Zend Framework tutorials) is Zend CastsDynamically creating a menu a sitemap and breadcrumbs.

Post to Twitter Tweet This Post Post to Plurk Plurk This Post Post to Yahoo Buzz Buzz This Post Post to Delicious Delicious Post to Digg Digg This Post Post to Facebook Facebook Post to MySpace MySpace Post to Ping.fm Ping This Post Post to Reddit Reddit Post to StumbleUpon Stumble This Post

Zend Framework Per-Module based settings

By Steven Lloyd Watkin, Friday 1st January 2010 10:40 pm

I’ve created a followup to this post which requires less configuration, please see Module Based Layout – Zend Framework.

When using the zend framework with modules, its obvious that if you’re running various (sub-)sites off the same application you don’t necessarily want the same layout scripts for each part. I decided to go with the following site structure:

/Application
    /controllers
        ...
    /models
    /modules
        /default
            /controllers
            /layout
                /scripts
            /views
                /scripts
        /anotherModule
            ...
    /scripts

The problem was setting up the layout scripts on a per-module basis. The answer came through using an Action Helper. Setting up the layouts on a per-module basis involves three steps:

  1. Application.ini (or similar configuration setup):
    admin.resources.layout.layoutPath = APPLICATION_PATH "/modules/admin/layouts/scripts"
    default.resources.layout.layoutPath = APPLICATION_PATH "/modules/default/layouts/scripts"
    member.resources.layout.layoutPath = APPLICATION_PATH "/modules/member/layouts/scripts"
    affiliate.resources.layout.layoutPath = APPLICATION_PATH "/modules/affiliate/layouts/scripts"
  2. Create your Action Helper:
    <?php
    /**
     * Sets the layout path on a per-module basis
     *
     * @author Lloyd Watkin <lloyd@evilprofessor.co.uk>
     * @since  2010-01-01
     */
    class Pro_Controller_Action_Helper_SetLayoutPath
        extends Zend_Controller_Action_Helper_Abstract
    {
        /**
         * Sets layout path based on module
         */
        public function preDispatch()
        {
        	$module = $this->getRequest()->getModuleName();
    
    	    if ($bootstrap = $this->getActionController()
    	                       ->getInvokeArg('bootstrap')) {
    
    	        $config = $bootstrap->getOptions();
    
    	        if (isset($config[$module]['resources']['layout']['layoutPath'])) {
    	            $layoutPath =
    	                 $config[$module]['resources']['layout']['layoutPath'];
    	            $this->getActionController()
    	                 ->getHelper('layout')
    	                 ->setLayoutPath($layoutPath);
    	        }
        	}
        }
    }
  3. And lastly boostrap the action helper:
    ...
        /**
         * Sets up layout scripts on a per-module basis
         */
        protected function _initLayoutHelper()
    	{
    	    $this->bootstrap('frontController');
    	    $layout = Zend_Controller_Action_HelperBroker::addHelper(
    	        new Pro_Controller_Action_Helper_SetLayoutPath());
    	}
    ...

Post to Twitter Tweet This Post Post to Plurk Plurk This Post Post to Yahoo Buzz Buzz This Post Post to Delicious Delicious Post to Digg Digg This Post Post to Facebook Facebook Post to MySpace MySpace Post to Ping.fm Ping This Post Post to Reddit Reddit Post to StumbleUpon Stumble This Post

Office Grid Computing using Virtual environments – Part 3

By Steven Lloyd Watkin, Friday 4th December 2009 11:37 pm

Introduction

I work in a company where we run many batch jobs processing millions of records of data each day and I’ve been thinking recently about all the machines that sit around each and every day doing nothing for several hours. Wouldn’t it be good if we could use those machines to bolster the processing power of our systems? In this set of articles I’m going to look at the potential benefits of employing an office grid using virtualised environments.

In part 2 we looked at the jobs a server will run, and how jobs should be configured in order to achieve greatest amount of processing whilst ensuring that each job is processed without fail.

Setting up your worker – or LiMP server

The next step in the process is to set up your virtual workers. For this I’m going to use an installation of centOS using VirtualBox. I’m going to install mySQL and PHP on the server, also known as a LiMP (Linux, mySQL, PHP) Server  (I may have made that name up).

  • Install VirtualBox on your windows machine (follow link)
  • Download and install centOS (current version 5.3) within a created virtual machine

There’s no point me going to this there’s probably 1,000′s of great tutorials out there (ok, here’s one: Creating and Managing  centOS virtual machine under virtualbox). The important point to note I suppose is that I called my virtual machine GridMachine.

As far as my choices of virtualisation client and operating system go there is no big compelling reason for each choice. VirtualBox is something I use on my home machine and is supported by the three major operating systems. I chose centOS as its a good stable OS and I use it on my own web server. I am a great believer in the right tools for the job (although I’m applying ‘use the quickest and easiest for you’ mentality here), so if operating system X runs your code quicker and more efficiently use that instead :)

Importantly make sure that your VM uses DHCP, otherwise for each new virtual machine would need to be configured separately which is something we don’t want.By using DHCP we don’t need to configure network settings individually for worker machines, DHCP will hand out IPs for you. Therefore you can copy your virtual machine about the office without worrying about setting each one up (this improves scalability and reduces worker administration).

The process you should aim to achieve would be to obtain a new physical machine, install VirtualBox, and then pretty much deploy the virtual image without much else. It might be wise to setup all your workers on a different subnet so that you can at least see how many machines are running. You’ll also need to set up your machines on a long lease or unlimited lease DHCP.

How to run Jobs on the worker

This is an interesting area and there are several valid methods for processing jobs on the worker. Here I’ll just discuss the two most obvious:

  • Perpetually running script: A script, be it a shell script, or a PHP script is executed once on the worker and runs as part of an infinite loop. I’ve discounted this method as one crash of the script and potentially your workers will cease to run without some sort of intervention.
  • Cron based script execution: Every X minutes the cron daemon kicks off a call to your script to get things going. Without some checking this could lead to many many copies of your worker script running.

My decision was to go with cron which kicks off a shell script every 10 minutes.  My shell script performs the following tasks:

  1. Get a process list and grep this for ‘php’. If not found then continue.
  2. Call your job code, in my case this would be something PHP based
  3. Worker script completes its run
  4. Ready to go again on the next appropriate call

My bash script looks something like the following:

#!/bin/sh
if ps ax | grep -v grep | grep php > /dev/null
then
    echo "Job is currently processing, exit"
else
    echo "Job is not running, start now"
    php yourJobProcessingScript.php
fi

Note: the echo’s are almost completely pointless, but may help the next person who comes along to try and edit them.

That concludes the set up of the worker virtual machine, quick, simple, and easy to copy to each new piece of hardware that is received. The ‘cleverness’ of the grid system really isn’t in the visualised OS, its all to do with the code created to process jobs, the job configuration, and in making sure that the job runs when appropriate (i.e. when the host is idle).

Setting up Windows to Initialise Workers

The first task is to work out the command required to run the virtual machine from the windows command line. If you’ve installed virtualBox in the default location and you’ve named your worker GridMachine then the command required to load up your worker is:

"C:\Program Files\Sun\VirtualBox\VBoxManage.exe" startvm GridMachine

However to run the script in a ‘headless’ state we need to use:

"C:\Program Files\Sun\VirtualBox\VBoxHeadless.exe" -startvm GridMachine --vrdp=off

This will start the virtual machine without the GUI and allow it to save state gracefully. The second argument turns off RDP so it doesn’t conflict with windows RDP, or give you a message about listening on port 3389. The virtual machine name is cAsE sEnSiTiVe!

Next, we’ll need to set windows up to kick off our worker VM once the machine has been idle. To do this (on Windows XP) you’ll need to go Start -> All Programs -> Accessories -> System Tools -> Scheduled Tasks as below:

scheduled tasks

Next click on ‘Add Scheduled Task’ followed by browse to add a custom program. Navigate to your VBoxManage script and click ok. Schedule your task for any of the options (we’ll change this in a minute) and continue. After skipping the next screen windows will ask you who you want to run this task, I’d suggest either ‘Administrator’ or creating a new privileged user. Remember we don’t want to interfere with the standard staff account on the machine at any point. Click next and check show advanced options for this task.

To the end of the run textbox add our ‘startvm GridMachine‘ string and ensure that run only when logged in is left unticked. Visit the schedule task next and change the schedule drop down to the option ‘when idle’, choose the amount of time you’d like the machine to be idle before moving on to the next tab.

Finally untick the option which states stop the task if it has been running X amount of time, but do tick the option to stop the task if the machine is no longer idle.

schedule

That’s it then for the windows host setup!

Summary

In this part we have set up a virtual machine to act as a worker, as well as the way in which we call and execute our job processing scripts (for myself a PHP script). From here we look at how to set up our copies of windows to start up the virtual machine in headless mode when the computer becomes idle, and save its state when the user resumes usage of the machine. Hopefully at this point you’re seeing how simple it is to set up such a system and are itching to get some experiments going yourself!

Next time

In Part 4 we’ll be looking at using tools to ensure that you’re running the latest version of the code and data sources so that obtained results are always up-to-date with the latest business information and logic.

Post to Twitter Tweet This Post Post to Plurk Plurk This Post Post to Yahoo Buzz Buzz This Post Post to Delicious Delicious Post to Digg Digg This Post Post to Facebook Facebook Post to MySpace MySpace Post to Ping.fm Ping This Post Post to Reddit Reddit Post to StumbleUpon Stumble This Post

Zend Framework: Fundamentals – Review

By Steven Lloyd Watkin, Saturday 28th November 2009 10:42 pm

My employer recently paid for a group of us developers to take the Zend Framework: Fundamentals course, here I’ll summarise my thoughts and opinions on the course for others. For those looking to save time, here’s my summary:

For developers who haven’t had time to look at the Zend Framework this course (Zend Framework: Fundamentals) offers a good overall picture of the framework introducing you to the key areas and giving enough information in order to continue. For those who have spent time looking at the framework and have followed one or two tutorials this course does not offer much beyond.

Background

I’ve been a PHP developer for around 5-6 years, and have started working with the Zend Framework on a component basis over the last 6 months. I’ve developed and/or been a developer on a couple of small Zend Framework MVC sites.  I’ll be honest, I haven’t had a huge amount of exposure to other frameworks from a coding point of view but have spent several hours researching the project websites and evaluating them.  The framework and the community surrounding Zend Framework it is quite exciting and there seem to be huge possibilities in where its going.

About the Course

The course is delivered over 9 two hour webex sessions (with a 10-minute break in the middle). The time is spent going through a set of slides provided by Zend with discussion at any time. You can use a microphone to talk to the instructor, but to be honest I didn’t see anyone use anything more than the chat window. In addition a VMWare Ubuntu machine is provided that has example code and projects set up an a trial version of Zend Studio. The course leader talks to attendees either over an integrated VoIP solution, or you can dial in using one of the many worldwide dial in numbers.

During the course the material consists of a brief overview of the Framework and the MVC pattern before heading into a sample guestbook application. The discussion demonstrated bootstrapping, Zend_Application, Db Tables, Database access, Forms, Filtering, ACL, Validating, etc, etc. Basically covering all the topics you’d require to get a basic site up an running all the time giving you the tools to go and get more advanced in the framework (although this did amount to ‘See the website’ much of the time).

Time is given to code up some examples, and to develop the ‘guestbook’ and simple ‘wiki’ application. Personally I felt that providing the code or each app and then asking us to develop what was essentially a copy alongside didn’t really provide a good learning experience. I would have preferred to develop an application similar, but not identical. to the example application with the benefit of having a guide to refer to. Alternatively building the applications from scratch with the demonstrator would of possibly led to more questions about why and how, thus giving a better understanding of the framework, after all you can look up specifics after the course.

The last lecture consisted of working on the wiki application with help/guidance from the instructor. After the course feedback was taken, it was emphasised several times through the course that Zend takes feedback very seriously, in fact apparently our version of the course was quite new. Some of the other developers in the company will be taking the course soon so it will be interesting to see if this has happened.

The course style was informal, allowed for feedback and collaboration between attendees and the instructor. The course leader was friendly, approachable (email addresses were shared for questions), and whilst his presentation from the slides was a bit shaky seemed fully competent in the framework. He was clearly someone who used the framework on a regular basis rather than someone who is taught to teach the course, I liked the ‘real world’ experience in that respect.

Overall Feeling

In some ways I found the course a waste of time, in others it was very handy. Hopefully I’ll get my reasons across clearly, and maybe provide some food for thought or useful feedback (knowing me this is unlikely!).

For myself this course was aimed at too low a level. Having gone through the quickstart guide, read Rob Allen’s Zend Framework in Action, and worked with the framework a little I didn’t really get anything too much. I would of liked the course to pick up from the end of the quickstart and develop additional skills.

That said, the course title does clearly state “Zend Framework: Fundamentals” and in that aspect the course achieves what it sets out to do. Other members of the development team that haven’t spent the time looking into the framework finished each session with enthusiasm and asked questions which was really nice to see.

All was not lost, it was good to spend time confirming the basic details of the framework and get to ask a couple of questions in areas where I wasn’t 100%. It was also time that I got to sit down each day and think about coding using the framework and future projects, something I wouldn’t of been able to do otherwise (can you imagine your company agreeing to that? :) ). Last but not least you also get a nice certificate from Zend to say that you attended the course (albeit by email).

Zend Framework Certification

This was one question that kept coming to mind during the course, would it prepare me for the certification? The quick, easy is a resounding No. The course instructor was quite clear on that with the additional advice that for the certification you should really be using the framework on a day to day basis and feel very comfortable and confident in its usage and methodologies.

Summary

Given everything I’ve written above, I’ll summarise everything in two easy bullet points:

  • New to Zend Framework: This course does exactly what you’d expect, it gives you a nice introduction to the framework and a good grounding on the basics from which you can build. The course seems to generate interest and enthusiasm for the framework amongst developers.
  • Used the Zend Framework: While it was nice to shore up some of the very basics I felt the time, effort, and funds to take the course could of been better spent elsewhere. It will be nice to see  Zend create a new higher level course to take developers to the next level – at least to the standard of certification and beyond. For that I would sign up immediately.

Post to Twitter Tweet This Post Post to Plurk Plurk This Post Post to Yahoo Buzz Buzz This Post Post to Delicious Delicious Post to Digg Digg This Post Post to Facebook Facebook Post to MySpace MySpace Post to Ping.fm Ping This Post Post to Reddit Reddit Post to StumbleUpon Stumble This Post













Panorama Theme by Themocracy

11 visitors online now
3 guests, 8 bots, 0 members
Max visitors today: 12 at 12:36 am UTC
This month: 12 at 03-09-2010 12:36 am UTC
This year: 66 at 15-07-2010 02:49 am UTC
All time: 66 at 15-07-2010 02:49 am UTC