JavaScript and CSS Helper Class - Zend Framework 2 (ZF2)

Greetings Programs,

In Zend Framework 1.0 I used a CSS and JavaScript loader. This allowed me load CSS and JavaScript based on an action and a controller. It also allowed me to load common CSS and JavaScript required for my headers, footers, and other common components that might be found on a page. I wanted to try and repeat this in ZF2. In this post I will walk through how I accomplished this.


I am currently learning ZF2 and am building from the skeleton application and from Rob Allen's album application. You can get my code from https://github.com/jdellostritto/zf2tutorial.git.

The factory loaders (CssLoader.php, and JsLoader.php) are based on the an example provide by Evan Coury.
http://blog.evan.pro/creating-a-simple-view-helper-in-zend-framework-2


First create your PHP helper files in this location:

/module/Application/src/Application/View/Helper/JsLoader.php
/module/Application/src/Application/View/Helper/CssLoader.php 


In this next step we need to do two things in the onBootstrap function of the Applicaiton/Module class (found in project at: /module/Application/Module.php). First we 'attach' or 'hook' to a MvcEvent called EVENT_ROUTE. Which as I understand it signifies the completion of the route creation. In the function we attach to the EVENT_ROUTE we are going to create two factories that will be accessible to our view. The goals is for us to be able to call our JsLoader and CssLoader classes from our layout.phtml file.
...
On to the helpers. We created two helpers earlier so it's time to fill these in. We extend the AbstractHelper which provides us the prototype functions to use.  We send three arguments to the loaders. The Request, PhpRenderer, and a RouteMatch. Our constructor must accept each of these and make them available. The invoke function then does the work. In this example all we have done in both the CssLoader and JsLoader is move the original skeleton code loading of headLink and headScript from layout.phtml into these two handy loaders.

...
...
...
The last step is to replace the original headLink and headScript in our layout.phtml file.
...
I am diving in to ZF2 and am putting together what I can from many sources. If this approach is flawed or there is a better way to do it please leave a comment.

Crom: Look. This... is all a mistake. I'm just a compound interest program. I work at a savings and loan! I can't play these video games!
Tron: 1982

JavaScript and CSS Helper Class - Zend Framework 2 (ZF2)

No comments:

Post a Comment