Posts tagged: framework

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'»

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.

Basically but invoking an instance of the front controller its possible to grab the router and assemble a url. Assemble is the function used in the view helper. The URL is built up from an array of module, controller, action, etc, followed by a second parameter of the route to use. The code is as follows:

<?php
/**
 * View helper which returns link category URL
 *
 * @author     Lloyd Watkin 
 * @since      25/01/2010
 * @package    ViewHelper
 * @subpackage LinksUrl
 */
class Pro_View_Helper_LinksUrl
    extends Zend_View_Helper_Abstract
{
	/**
	 * Returns link category URL
	 *
	 * @param  Doctrine_Record $category
	 * @param  string          $module
	 * @param  string          $controller
	 * @param  string          $action
	 * @return string Url
	 */
    public function linksUrl($category, $module = 'www',
        $controller = 'links', $action = 'index')
    {
    	$router = Zend_Controller_Front::getInstance()->getRouter();

        return $router->assemble(array(
            'module'     => $module,
            'controller' => $controller,
            'action'     => $action,
            'category'   => "{$category->id}-{$category->name}",
        ), 'www-index');
    }
}

Another way to do this is to invoke Zend_View_Helper_Url itself and call the Url method (if you want to use the helper itself). This can be done by using the following code:

<?php
/**
 * View helper which returns link category URL
 *
 * @author     Lloyd Watkin 
 * @since      25/01/2010
 * @package    ViewHelper
 * @subpackage LinksUrl
 */
class Pro_View_Helper_LinksUrl
    extends Zend_View_Helper_Abstract
{
	/**
	 * Returns link category URL
	 *
	 * @param  Doctrine_Record $category
	 * @param  string          $module
	 * @param  string          $controller
	 * @param  string          $action
	 * @return string Url
	 */
    public function linksUrl($category, $module = 'www',
        $controller = 'links', $action = 'index')
    {
    	$link = new Zend_View_Helper_Url();

        return $link->url(array(
            'module'     => $module,
            'controller' => $controller,
            'action'     => $action,
            'category'   => "{$category->id}-{$slug}",
        ), 'www-index');
    }
}

Both almost identical. Not a hard thing to do in the framework but can catch you out ;)

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.

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());
    	}
    ...

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.

Log to DB using Zend Framework

By Steven Lloyd Watkin, Tuesday 14th April 2009 9:06 pm

I’ve managed to get a site up and running with the Zend Framework, everything is logging nicely to FireBug/FirePHP so next step was to log to the DB. I also wanted to log some additional information using the framework such as user agent, date and time, get and post variables. So to extend the manual a little here’s what I did:

// Set up logging to DB
$db = Zend_Registry::get('dbAdapters');
$db = $db['general'];

$columnMapping = array( 'priority' => 'priority',
'message' => 'message',
'datetime' => 'timestamp',
'user_agent'=> 'user_agent',
'get_vars' => 'get_vars',
'post_vars' => 'post_vars',
'site' => 'site'
);

$writerDb = new Zend_Log_Writer_Db($db, 'error_logging', $columnMapping);
$logger = new Zend_Log($writerDb);

$logger->setEventItem('datetime',date('Y-m-d H:i:s'));
$logger->setEventItem('user_agent',$_SERVER['HTTP_USER_AGENT']);
$logger->setEventItem('get_vars',print_r($_GET,true));
$logger->setEventItem('post_vars',print_r($_POST,true));
$logger->setEventItem('site',SITE);

$logger->info('Informational message');

Where the array keys in $columnMapping are my column names. ‘Priority’ and ‘message’ are understood by Zend_Log_Writers but the additional fields were added to give me some additional information.

Obviously this assumes that you have logging working using one of the other writers first :)

Panorama Theme by Themocracy

11 visitors online now
11 guests, 0 members
Max visitors today: 35 at 02:19 pm UTC
This month: 42 at 11-03-2010 02:50 am UTC
This year: 42 at 11-03-2010 02:50 am UTC
All time: 42 at 11-03-2010 02:50 am UTC