Please visit my new campsite listing site ukcampingmap.co.uk


Batch including headscripts and links in Zend Framework

A bit of a dull post to break my silence with, but after a summer away, it’s back to the grindstone of earning a living through programming. Fingers crossed I’ll be given the opportunity to work again on a website I finished ages ago, fixing all the things I did badly and adding some enhancements.

I used Zend framework for the back-end of the site and first time around I had a very rudimentary grasp of how to use it, but no real in depth understanding of its finer points. I’m now finding that I did a lot of things the long way round (eg typing out JSONs by hand  rather than using the Zend_JSON class to build them automatically). One major bugbear I had was that I was adding all my javascript and css files individually to the document head, and that the syntax for doing so in Zend wasn’t really any more concise than just hard coding <link rel=”stylesheet” ….

So now I’m revisiting Zend the first thing I’ve done is write a couple of view helpers to batch add javascript and css files, which I thought I’d share here.

<?php

class Zend_View_Helper_IncludeStyles extends Zend_View_Helper_Abstract {

   public function includeStyles($folder)
   {
     $results = array();
     $handler = opendir(getenv("DOCUMENT_ROOT") . "/css/" . $folder);
     while ($file = readdir($handler)) {
       if ($file != "." && $file != "..") {
         $this->view->headLink()->appendStylesheet('/css/' . $folder . '/' . $file);
       }
     }
     closedir($handler);
   }
}
<?php

class Zend_View_Helper_IncludeScripts extends Zend_View_Helper_Abstract {

  public function includeScripts($folder)
  {
    $results = array();
    $handler = opendir(getenv("DOCUMENT_ROOT") . "/js/" . $folder);
    while ($file = readdir($handler)) {
      if ($file != "." && $file != "..") {
        $this->view->headScript()->appendFile('/js/' . $folder . '/' . $file);
      }
    }
    closedir($handler);
  }
}

No related posts.

Leave a Reply

Security Code: