Meta Tag Controller Plugin for Zend Framework

Again on the never ending quest to DRY up my code, next in the targets are the head sections MetaTags!

Following on from my last post which used Zend_Config_Xml, we shall do the same for each pages title, description, and keywords.

In your application/configs directory, create a file named meta.xml :

<?xml version="1.0" encoding="UTF-8"?>
     <title>My Home Page</title>
     <description>This is my websites home page</description>
       <description>BUYING A HOUSE</description>
       <title>Buying a property</title>
       <description>SELLING A HOUSE</description>
       <title>Selling a property</title>

Create a Controller Plugin in your library. For me, it’s /library/TTB/Plugin/Meta.php :

class TTB_Plugin_Meta extends Zend_Controller_Plugin_Abstract
 public function preDispatch(Zend_Controller_Request_Abstract $request) 
     $config = new Zend_Config_Xml(APPLICATION_PATH.'/configs/meta.xml','meta');
     $uri = $request->getPathInfo();
     $defaults = true;
     $view = Zend_Controller_Front::getInstance()
     foreach ($config->uris->uri as $meta) 
       if($meta->page == $uri) 
         $view->headMeta()->appendName('title', $meta->title);
         $view->headMeta()->appendName('description', $meta->description);
         $defaults = false;
     if($defaults == true)
       $view->headTitle('My Awesome Website');
       $view->headMeta()->setName('description','This is the default');
       $view->headMeta()->setName('keywords','zend framework, php, delboy1978uk');
   catch(Exception $e)
     throw new Exception('Unable to set Meta Tags');

We need to register the plugin in our application.ini :

autoloaderNamespaces[] = "TTB_"
resources.frontController.plugins.Meta = "TTB_Plugin_Meta"

Finally we initialise the Plugin in our bootstrap :

protected function _initMeta()
    $meta = new TTB_Plugin_Meta();

You should already have this in your layout file, but if not you want this in the <head> section of your layout.phtml :

echo $this->headTitle();
echo $this->headMeta();

There we have it! Meta Tags – sorted!
Again Brownie Points will be awarded to he/she who replies with code to populate the XML from DB data!

If you need to override the defaults from within a controller, (eg. if you were populating the title with db data), you can use this sort of thing:

$this->view->headTitle('Dynamic Page Title', 'SET');
 $this->view->headMeta()->setName('description','Dynamic Description');
 $this->view->headMeta()->setName('keywords','dynamic keywords');

Cheers amigos! 😀