Oct 21 2009

Sorting a Zend Navigation container by Page dates

I’ll introduce this topic with a warning – This article doesn’t show you how to completely reorder your entire Navigation, it does however show you how you could populate a new container from an existing one and reorder it.

Zend Navigation currently doesn’t allow you to nominate a default Navigation Container class. So while we could extend the Zend_Navigation_Container creating our own customised one, you’d almost have to duplicate the code for the Zend Page and Zend Container classes to do a thorough job, as they both call each other – so won’t know to use your new one.

My goal was to achieve:

  • a container of all pages in my navigation configuration (ignoring hierarchy)
  • exclude pages that had sub pages (so I only had the leaves on the branch so to speak)
  • order these pages by a date set for each page in the nav configuration

Step 1 – Add dates to Navigation configuration

You can add new properties to Zend Navigation Pages without needing to do anything. See my “dateadded” in the example below on some pages.

                    <security>
                        <label>Security</label>
                        <module>computers</module>
                        <controller>security</controller>
                        <action>index</action>
                        <pages>
		                    <password>
		                        <label>Password generator</label>
		                        <module>computers</module>
		                        <controller>security</controller>
		                        <action>password-generator</action>
		                        <dateadded>01/08/2009</dateadded>
		                    </password>
                            <encrypt>
		                        <label>Hash generator</label>
		                        <title>Hash generator (string encryption)</title>
		                        <module>computers</module>
		                        <controller>security</controller>
		                        <action>encrypt</action>
		                        <dateadded>25/08/2009</dateadded>
		                    </encrypt>
		                </pages>
                    </security>

Step 2 – Create a custom container type

By creating a custom container extending Zend_Navigation_Container we can add our own sorting function. The trick of this is converting the dates to the linux time stamp i.e. number of seconds since 1 January 1970. This is also a logical place to but build a function to extract lowest level pages from another container. This one class services all three of my requirements.

class Utilitiesman_Navigation_Container_Utilities extends Zend_Navigation_Container
{
	public function addLowestPages($page) {
		$iterator = new RecursiveIteratorIterator($page,RecursiveIteratorIterator::SELF_FIRST);
		foreach ($iterator as $page) {
			// don't add page if it has children
			if(!$page->hasPages()) {
				$lowestPages[] = $page;
			}
		}
		$this->addPages($lowestPages);
	}
 
    public function sortByDate($property = 'dateadded')
    {
        $newIndex = array();
        $index = 0;
 
        foreach ($this->_pages as $hash => $page) {
            $pageDate = $page->get($property);
            if(Zend_Date::isDate($pageDate)) {
                $date = new Zend_Date($pageDate);
                $timestamp = $date->getTimestamp();
                $newIndex[$hash] = $timestamp;                
            } else {
                // there wasn't a valid date for this page, use an incremental number start at 0
                $newIndex[$hash] = $index;
                $index++;
            }
        }
 
        //sort the array using those timestamp versions of the dates
        arsort($newIndex);
        $this->_index = $newIndex;
        $this->_dirtyIndex = false; // flag index as clean - prevent default sort
    }
 
}

Step 3 – Call it and render the result

This is all done within the context of a view script (the layout in my case) I should mention:

$containerByDate = new Utilitiesman_Navigation_Container_Utilities();
$rootPage = current($this->navigation()->getContainer()->getPages());
$containerByDate->addLowestPages($rootPage);
$containerByDate->sortByDate();
echo $this->navigation()->menu()->render($containerByDate);

To see a cool example of this in action check out the calculator section of my utilities man website, or any section mind you.

utilities man - calculators

My implementation is a little more complex than this though, I’m using a partial view script for the menu and I’m also only displaying pages under the section your on.

Share and Enjoy:
  • DZone
  • Digg
  • del.icio.us
  • Technorati

Aug 16 2009

Zend_Navigation Tricks: True tab navigation with sub menus – Part 3

Part 3: Implementing jsTree which uses jQuery (optional javascript expand/collapse)

This is a completely optional step in this series and really has nothing to do with Zend Framework because by this based on the client side we have all the HTML we need.

What we’ll be doing is setting up jsTree a jQuery tree component that can do much more than we’ll be using it for, it’s probably overkill but the best I came across when I was looking on this occasion.

You need jQuery:

$this->headScript()->appendFile($this->baseUrl . '/scripts/jquery-1.3.2.min.js', 'text/javascript');

Setup the jsTree javascript and css files if $nav2Container is set (see Part 2)

// append nav2 menu components if $activeContainer is set for the menu
if(isset($nav2Container)) {
    $this->headScript()->appendFile($this->baseUrl . '/scripts/jstree/css.js', 'text/javascript');
    $this->headScript()->appendFile($this->baseUrl . '/scripts/jstree/tree_component.min.js', 'text/javascript');
    $this->headLink()->appendStylesheet($this->baseUrl . '/scripts/jstree/tree_component.css', 'screen');
}

Render the Style and Script files we setup earlier:

        echo $this->headStyle() . "\n";
        echo $this->headScript() . "\n";

Some of this code below is a repeat from previous parts but its better to see this all in context. I’ve added a couple bit of JavaScript to achieve the following:

< ?php
        	// render nav2 container and menu if not on the homepage
        	if(isset($nav2Container)) {
        ?>
        <div id="nav2Container">
        	< ?php 
        		$this->navigation()->menu()->setMinDepth(null)->setMaxDepth(null);
        		echo $this->navigation()->menu()->renderMenu($nav2Container,array('ulClass' => 'nav2'));
        	?>
        	<script type="text/javascript">
        	$(function () {
        			// setup each active <li> with an id
        			var $active_li = $(".nav2 li.active");
        			var $active_li_id = new Array();
            		for( var i = 0, n = $active_li.length;  i < n;  ++i ) {
                		var $element = $active_li[i];
                		$active_li_id[i] = "nav2_active_" + i;
                		$($element).attr("id", $active_li_id[i]);
            		};
        			// configure and initialise 
        			$(".nav2").tree({
              			data  : {type : "predefined"},
            	  		opened : $active_li_id,
        	      		path : "<?php echo $this->baseUrl . '/scripts/jstree/'; ?>",
              			ui : {theme_name : "toolbox"},
        	      		rules : {   
                			metadata : "mdata",
                			use_inline : true
              			}
        			});
        		});
        	</li></script>
        </div>
        < ?php
        	}
        ?>

I’m using version 0.9.8 of jsTree but I’m looking forward to version 0.9.9 which will apparently alleviate some of my design/performance concerns, as the script loads this default theme and then the custom theme, rather than just the custom theme.

If I’ve missed anything and this doesn’t work, please let me know!

Share and Enjoy:
  • DZone
  • Digg
  • del.icio.us
  • Technorati

Aug 16 2009

Zend_Navigation Tricks: True tab navigation with sub menus – Part 2

Part 2: Rendering the sub menus (relevant to the active tab).

This is where we employ another trick because the Zend_Navigation menu view helper does provide an option to render the active menu, but it is meant literally not the active branch of the menu like we’re trying to achieve.

In the layout we need to get the root level pages then we assume the 1st one is Home and root of all other navigation items. After this we loop through the pages below Home to find the active one and set this as the $nav2Container which we’ll use next.

layout.phtml

// find the active page/container under the rootPage (Home) for nav2 menu
$rootPage = current($this->navigation()->getContainer()->getPages());
$pages = $rootPage->getPages();
foreach($pages as $page) { 
	if($page->isActive(true)) { 
		$nav2Container = $page; 
	}
}

Now that we know what the root of this sub menu should be we can use the helpers to render it (this is also in your layout file).

if(isset($nav2Container)) {
    echo $this->navigation()->menu()->renderMenu($nav2Container,array('ulClass' => 'nav2'));
};
Share and Enjoy:
  • DZone
  • Digg
  • del.icio.us
  • Technorati

Aug 16 2009

Zend_Navigation Tricks: True tab navigation with sub menus – Part 1

It is some what tricky with the Zend_Navigation menu helpers to set up your typical tab-based navigation with sub pages relevant to the tab your on, as seen below. But it’s not far difficult so don’t be put off, hopefully the view helpers will improve over time.

tab-menu-example

In the mean time this is a 3 part series in achieving the navigation I set up in utilitiesman.com as seen above.

Part 1: Setting up the navigation, and rendering the tabs.

Set up your navigation configuration, I’ve done this in xml.

< ?xml version="1.0" encoding="UTF-8"?>
<configdata>
    <nav>
        <label>Home</label>
        <module>default</module>
	<controller>index</controller>
	<action>index</action>
        <pages>
            <computers>
                <label>Computers</label>
                <module>computers</module>
                <controller>index</controller>
                <action>index</action>
                <pages>
                    <networking>
                        <label>Networking</label>
                        <module>computers</module>
                        <controller>networking</controller>
                        <action>index</action>
                        <pages>
		                    <ipaddress>
		                        <label>IP Address</label>
		                        <module>computers</module>
		                        <controller>networking</controller>
		                        <action>ipaddress</action>
		                    </ipaddress>
		                    <ping>
		                        <label>Ping</label>
		                        [... code removed for example ...]
		                    </ping>
     	                            [... code removed for example ...]
		                </pages>
                    </networking>
                    <security>
                        [... code removed for example ...]
                    </security>
                </pages>
            </computers>
            <measures>
                [... code removed for example ...]
            </measures>
        </pages>
    </nav>
</configdata>

In your bootstrap file you’ll need setup the navigation and load your navigation config:

$navigationConfig = new Zend_Config_Xml('./application/Config/navigation.xml');
$navigation = new Zend_Navigation($navigationConfig);

Assuming you’re making use of the Zend_Layout this would go in your template

$this->navigation()->menu()->setPartial(array('nav1.phtml','default'));
echo $this->navigation()->menu()->render();

This is my partial menu template which is where some minor trickery is performed to see the Home page and first level pages in a single <ul> for easy application of CSS to make the <li>’s look like tabs. This is the “nav1.phtml” referred to in the layout.

    echo '<ul id="nav1">';
    // loop root level (only has Home, but later may have an Admin root page?)
    foreach ($this->container as $page) {
        // check if it is active (not recursive)
        $isActive = $page->isActive(false);
        $liClass = $isActive ? ' class="active"' : '';
        echo '<li ' . $liClass . '>' . $this->menu()->htmlify($page) . '</li>', PHP_EOL;
        // loop next level
        foreach ($page as $page) {
            // check if it is active (recursive)
            $isActive = $page->isActive(true);
            $liClass = $isActive ? ' class="active"' : '';
            echo '<li ' . $liClass . '>' . $this->menu()->htmlify($page) . '</li>', PHP_EOL;
        }
    }
    echo '</ul>';

What the partial template above renders is something like this, neatly all in a single hieratical level..

<ul id="nav1">
    <li><a ...>Home</a></li>
    <li class="active"><a ...>Computers</a></li>
    <li><a ...>Measures</a></li>
</ul>
Share and Enjoy:
  • DZone
  • Digg
  • del.icio.us
  • Technorati

Aug 16 2009

Zend_Navigation Trick: Sub pages only breadcrumb

The most logical place to render your breadcrumb from is your master layout… However it’s unlikely you’ll ever want to render to on your home page right? I mean what is the point of seeing just “Home”.

This can be simply achieved using a partial template to render your breadcrumb. The code below should explain things for you, but leave a comment if you would like further explanation.

bootstrap.php

$navigationConfig = new Zend_Config_Xml('./application/config/navigation.xml');
$navigation = new Zend_Navigation($navigationConfig);

navigation.xml

< ?xml version="1.0" encoding="UTF-8"?>
<configdata>
    <nav>
        <label>Home</label>
        <module>default</module>
		<controller>index</controller>
		<action>index</action>
        <pages>
            <computers>
                <label>Computers</label>
                <module>computers</module>
                <controller>index</controller>
                <action>index</action>
                <pages>
                    <networking>
                        <label>Networking</label>
                        <module>computers</module>
                        <controller>networking</controller>
                        <action>index</action>
                        <pages>
                [...]
        </pages>
    </networking></pages></computers></pages></nav>
</configdata>

layout.phtml

echo $this->navigation()->breadcrumbs()->setPartial(array('breadcrumb.phtml', 'default'));

breadcrumb.phtml

// only render if there is more than 1 page in the breadcrumb
if (count($this->pages) > 1) {
    $links = array();     
    foreach ($this->pages as $page) {
        $links[] = $this->breadcrumbs()->htmlify($page);
    }
    echo implode(' &gt; ', $links);
}
Share and Enjoy:
  • DZone
  • Digg
  • del.icio.us
  • Technorati

Dec 5 2008

Wheres the Model in Zend Frameworks MVC?

Don’t get me wrong ZF is my PHP framework of choice however it’s really lacking the Model concept from the MVC design pattern! The Model is where you should be implementing your business logic, data validation for example…

Zend Framework implements interfaces for filtering and validation on it’s Form components. The framework however lacks these interfaces on other components suitable to implement a true MVC design pattern where the validation would occur in the Model.

The interfaces on the Form component aren’t suitable for complex applications where a single model is used by multiple forms in the application. Say you store your email addresses in a single table in your database, but in your application, multiple ‘objects’ have email addresses associated with them… Should u have to setup the email address validation 10 times for each form the field is used in? I don’t think so…
I’m yet to work out the perfect solution to this unfortunately, but some ideas I’ve had are:

  1. Store you Form Elements in your model classes and add them to your forms in the Controller as required.
  2. Create you own model class with it’s own validation interfaces.

The second option is what I’ve done in past applications and I’m just about to start my next and decided to see if there is a better solution out there… The best article I’ve found was at techfounder and was proposing the second option as well and had some good examples. And model class approach on jmgtan.. However both still leave a lot to be desired :(

I’d be interested to hear any other ideas, or see any other bookmarks you have!

Share and Enjoy:
  • DZone
  • Digg
  • del.icio.us
  • Technorati

Sep 14 2007

Part 1: Access Control List – a model to solve all models!

I’m involved in the development of a large web application (using Zend Framework) with many different types of entities inside! Some functions performed on these entities should be accessible to some users but not others… To make things more interesting users can assign other users with rights to these entities…

We’re going for a hands off user administration model where users register themselves, create things themselves, and give other users access to them.. THEMSELVES!

This article is Part 1 of many as I design and create a Zend Controller Plugin designed in simple terms to check if the user is allow to do whatever the hell they’re trying to do… I’d like to reuse it forever and a day though, so we need more functionality and flexibility…. My list of requirements goes on:

  • Simplified everything – Can we use 1 line to kick off all ACL checks?
    No one likes having to include the ACL checking at the top of everything, and worse yet implicitly define what it is the page does, or who should access it… So we’ll require none of this!!
  • Anonymous users should not be discriminated against!
    Anonymous users should be treated just like any other authenticated user – their access should be checked using the same process, and stored in the same manner! Examples of benefits:

    • Simplifies management the ‘anonymous user’ by using a normal role.
    • Logging (e.g. Ann performed this action) and metadata (e.g. updated by Ann) functions don’t need to cater for the irregularity of an ‘unknown’ user.
    • Explicit access to entities can checked/stored in the same way as normal users. For example – I want to make my Social networking profile publically viewable.
  • Users should have generic roles!
    This means even though some users may not have implicit access to some entities, they can still have access! This is a more typically found smaller applications so definitely needs to be included.. Some example usage scenarios are:

    • Administrators – Access to everything!
    • Support staff – Application support staff may need to see ‘stuff’; manage user accounts.
    • Moderators/Editors – Can approve anything/Can edit anything.
    • Anonymous – Allowed to see log in page.
  • Users might have explicit privileges to supercede generic ones!
    This provides a way for use to either grant or restrict access to specific entities regardless of the users generic role. An example scenarios:

    • “Support staff” should b restricted from managing Administer accounts.
    • A user by default can’t edit ‘comments’, but can edit their own.
  • Actions can depend on actions too!
    If a user has permission to perform a certain action, there may be other actions they should also have access to automatically. Example scenarios:

    • The ‘Register user’ action uses another action for AJAX validatio
    • The ‘Latest news’ action has an equivalent RSS/ATOM feed through another action
  • Required ID checking for actions (soo not typically in scope, I know!)
    I need to explore this idea a little further (I’m not sure it will make the cut yet)… This typically wouldn’t be included in scope for a access control class! BUT… In this ACL model we’ll allow for checking if a user has access an perform an action on a specific entity. And we need to know the entity’s ID and what the entity is right?… So it seems only logically to store what actions REQUIRE what types of entity ID’s… Maybe we’ll go so far as to check they exist?

Assumptions

I’ll never have access requirements more specific than the action being requested!

Basically my ACL will define a users permission (ie. can access OR can’t access) to a specific action and its relationship with an entity if applicable. It will not be able to say a user can only partially see/run the action.

This will likely however still be achievable within this application itself. But it’s definitely outside of the scope of this particular Controller Plugin.

By ‘action’ I mean the standard route in Zend Framework (ie. Module/Controller/Action). So we’ll assume I’ll always be using it…

End note

Obviously every project always has unique requirements so I don’t anticipate what I’m working on will suit EVERYONE… But considering I’m designing this for maximum reused I would very much appreciate hearing the many weird and unique access control requirements you’ve encountered.

While I’m working on it I would like to incorporate the anything that is realistically reusable…

Share and Enjoy:
  • DZone
  • Digg
  • del.icio.us
  • Technorati

Sep 6 2007

Zend_Auth bug with MS SQL

Currently Zend_Auth won’t work if you’re using a Micrsoft SQL Server database for storing your account credentials.

This is because of a bug in the \Zend\Auth\Adapter\DbTable.php specifically in the authenticate() function. The SQL Statement it generates is not MS SQL friendly:

SELECT "users".*, "credential" = 'mypass' AS zend_auth_credential_match
FROM "users"
WHERE ("identity" = 'me')

Consequently causing the following error:

Incorrect syntax near the keyword 'AS'.

The good news is the code below can be used as a replacement in this function until the Zend Framework team get a chance to fix it themselves. It has been tested in MS SQL 2005 but I imagine it should work well in another DB (but test this yourself and comment back!).

// build credential expression
if (empty($this->_credentialTreatment) || (strpos($this->_credentialTreatment, "?") === false)) {
    $this->_credentialTreatment = '?';
}
 
$credentialExpression = new Zend_Db_Expr(
    $this->_zendDb->quoteInto('(CASE WHEN '
        . $this->_zendDb->quoteIdentifier($this->_credentialColumn)
        . '=' . $this->_credentialTreatment, $this->_credential)
        . ' THEN 1 ELSE 0 END) '
        . ' AS ' . $this->_zendDb->quoteIdentifier('zend_auth_credential_match'));
 
// get select
$dbSelect = $this->_zendDb->select();
$dbSelect->from($this->_tableName, array('*', $credentialExpression))
         ->where($this->_zendDb->quoteIdentifier($this->_identityColumn) . ' = ?', $this->_identity);

The code above generates the following MS SQL friendly SQL statement:

SELECT "users".*, CASE WHEN "credential" = 'mypass' THEN 1 ELSE 0 END AS zend_auth_credential_match
FROM "users"
WHERE ("identity" = 'me')

There is an issue open with the team if you’re interested in reading it (and please vote for it to be resolved).

Share and Enjoy:
  • DZone
  • Digg
  • del.icio.us
  • Technorati

Aug 24 2007

Buzzzzzz on frameworks and libraries

There’s a lot of buzz with Frameworks and Libraries these days, and rightly so, without them some projects I’ve worked on would still be under construction!!! Developing with frameworks and libraries will save you time in both development and testing.

The abundance of functionality some provide often mean you’ll end up with a better end product. Not all clients can afford the time and money required to have developers work from the ground up. With the benefits of useful frameworks/libraries your clients will get more than they wanted for less than you quoted (or you could keep the float).

I could go on for hours listing examples I’ve played with over the years, but some of my personal favourites are:

Zend Framework
http://framework.zend.com

The leading open-source PHP framework has a flexible architecture that lets you easily build modern web applications and web services.

Yahoo! User Interface Library (YUI)
http://developer.yahoo.com/yui/

a set of utilities and controls, written in JavaScript, for building richly interactive web applications using techniques such as DOM scripting, DHTML and AJAX. The YUI Library also includes several core CSS resources.

jQuery
http://jquery.com/

jQuery is a fast, concise, JavaScript Library that simplifies how you traverse HTML documents, handle events, perform animations, and add Ajax interactions to your web pages. jQuery is designed to change the way that you write JavaScript.

I realise there is a great deal more I could and should be listing here… and probably some much better?! Please leave a comment I’ve love to here your favorites… and I’ll try include them in future posts!

Share and Enjoy:
  • DZone
  • Digg
  • del.icio.us
  • Technorati