Raza Mehdi's Blog

Zend Framework

How to Develop a Template System in Zend Framework Application

by on Jan.31, 2013, under PHP, Zend Framework

In this post, i will show you how to create a template system in a Zend Framework appplication using Zend_Layout & Zend_View. The Zend Framework version being used is 1.12. I would assume that you have created a Zend Framework application that has already layout enabled. The following is the default folder structure of a Zend Framework application:

zfProject_pic

To implement the template system, we would need to change the folder structure as well. I change layouts & views sub-folders of the applications folder in the following way:

zfProject_pic2

Now we must sure that Zend Framework loads this template & layout structure by default. Open the application/Bootstrap.php file, and insert the following code:

<?php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{

     private $_theme = '';

     public function __construct($application) {
          $this->_theme = 'blue';
          parent::__construct($application);
     }

     protected function _initLayout() {
          $options = array(
               'layout'        => 'layout',
               'layoutPath'    => APPLICATION_PATH . '/layouts/scripts/' . (!empty($this->_theme) ? $this->_theme : 'default'),
               'contentKey'    => 'content'
          );

          $layout = Zend_Layout::startMvc($options);
          return $layout;
     }

     protected function _initView() {
          $view = new Zend_View();

          $view->doctype('XHTML1_STRICT');
          $view->setBasePath(APPLICATION_PATH . '/views/' . (!empty($this->_theme) ? $this->_theme : 'default'));
          $view->addHelperPath(APPLICATION_PATH . '/views/helpers');
          $view->theme = (!empty($this->_theme) ? $this->_theme : 'default');

          $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
          $viewRenderer->setView($view);

          return $view;
     }

}

Now we have made the necessary adjustments to the Bootstrap.php file, lets turn our attention to the template configuration. As you can see in the previous screenshot, there is a template.xml for every template folder in the application/views folders. I simply entered in the list of CSS & Javascript files in the specific template folder. Please note this may vary:

<?xml version="1.0" encoding="UTF-8"?>
<template>
     <stylesheets>
          <stylesheet>layout.css</stylesheet>
          <stylesheet>print.css</stylesheet>
          <stylesheet>jquery-ui.min.css</stylesheet>
     </stylesheets>

     <scripts>
          <script>jquery.min.js</script>
          <script>jquery-ui.min.js</script>
          <script>script.js</script>
     </scripts>
</template>

Now we need to create a view helper to load the files listed in the template.xml folder. Create a file called LoadTemplate.php in the applications/views/helpers folder, and write the following code:

<?php

class Zend_View_Helper_LoadTemplate extends Zend_View_Helper_Abstract {

     public function loadTemplate($template) {

          $templateData = new Zend_Config_Xml(APPLICATION_PATH . '/views/' . $template . '/template.xml');

          $scripts = $templateData->scripts->toArray();
          $stylesheets = $templateData->stylesheets->toArray();

          if(is_array($scripts) && !empty($scripts)) {
               foreach($scripts as $script)
                    $this->view->headScript()->appendFile(APPLICATION_PATH . '/views/' . $template . '/js/' . $script);
          }

          if(is_array($stylesheets) && !empty($stylesheets)) {
               foreach($stylesheets as $stylesheet)
                    $this->view->headLink()->appendStylesheet(APPLICATION_PATH . '/views/' . $template . '/css/' . $stylesheet);
          }
     }
}

Finally we simply update the layout.phtml files in our desired template folders with the following code:

<?php $this->loadTemplate($this->template); ?>
<html>
<head>
<?php
echo $this->headTitle();
echo $this->headScript();
echo $this->headLink();
?>
</head>
<body>
<?php
echo $this->layout()->content;
?>
</body>
</html>

Thats it. You now have a basic templates system in a Zend Framework application. You can also modify it to your own requirements.

Looking forward to your feedback in the comments :) .

Leave a Comment more...

How to implement SSL in Zend Framework?

by on Jun.21, 2011, under Zend Framework

Hi guys!

At work, i was working on an e-commerce application in Zend Framework. I had to implement SSL on login, cart and checkout pages. While searching on the task, i found the following post on stackoverflow.com. This implements SSL on specific urls of your application. I am gonna assume that you have a working zend framework application configured.So, if you want to have SSL enabled for the login page of your application:

First, enter the following code in your ssl.ini file. We will parse it later through the Bootstrap.php file.


ssl.modules.default.require_ssl = true  //-> entire module requires SSL
ssl.modules.default.Index.require_ssl = true  //-> entire controller requires SSL
ssl.modules.default.Index.login.require_ssl = true  //-> single action requires SSL

Next create a file Ssl.php in library/Application/Controller/Plugin folder. In the file, write the following code:

class Application_Controller_Plugin_Ssl extends Zend_Controller_Plugin_Abstract
{

 public function preDispatch ( Zend_Controller_Request_Abstract $request )
 {

 $shouldSecureUrl = false;

 //get the config settings for SSL
 $options = new Zend_Config_Ini(APPLICATION_PATH.'/configs/ssl.ini');
 $options = $options->ssl;

 //if config is empty, exit
 if (!is_object($options))
 return;

 //simpler to use
 $options = $options->toArray();

 //only use it production environment
 if ( APPLICATION_ENV == 'production' )
 {

 if (

 ( isset($options['modules'][$request->module]['require_ssl']) && $options['modules'][$request->module]['require_ssl'] )  ||
 ( isset($options['modules'][$request->module][$request->controller]['require_ssl']) && $options['modules'][$request->module][$request->controller]['require_ssl'] )  ||
 ( isset($options['modules'][$request->module][$request->controller][$request->action]['require_ssl']) && $options['modules'][$request->module][$request->controller][$request->action]['require_ssl'] )

 )
 {

 $shouldSecureUrl = true;

 }

 if ( $shouldSecureUrl )
 {

 $this->_secureUrl($request);

 }
 }
 }

 protected function _secureUrl ( Zend_Controller_Request_Abstract $request )
 {

 $server = $request->getServer();
 $hostname = $server['HTTP_HOST'];

 if ( ! $request->isSecure() )
 {
 $url = Zend_Controller_Request_Http::SCHEME_HTTPS . "://" . $hostname .
 $request->getPathInfo();

 $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
 $redirector->setGoToUrl($url);
 $redirector->redirectAndExit();
 }
 }
}

Now, in the Bootstrap.php file, add a function called _initPlugins() and add the following code:

$frontController = Zend_Controller_Front::getInstance();
$frontController->registerPlugin( new Application_Controller_Plugin_Ssl());
6 Comments more...

Get list of all modules with all controllers and actions in Zend Framework

by on Jan.06, 2011, under Zend Framework

Hi guys!

Finally back after a long time. I have been really busy at work.  In one of the projects, i had to get list of modules plus controllers and their respective actions for ACL configuration purposes .. I implemented the said task using action helper and controller plugin in Zend Framework. I am listing the Action helper code here. Also, when done with ACL, i will post that code here as well …

Before getting started, i am going to assume that you have configured Zend Framework installation on your local machine and setup your application through a virtual host.

First, open the Bootstrap.php in your application directory and put the following code:

<?php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{

    protected function _initAutoLoad(){
        $autoLoader = Zend_Loader_Autoloader::getInstance();
        $autoLoader->registerNamespace('Application_');

        return $autoLoader;
    }

    protected function _initActionHelpers() {
        Zend_Controller_Action_HelperBroker::addHelper(new Application_Action_Helper_AssetsList());
    }

Now do the following:

  1. Create a folder called Application in your site’s library folder.
  2. Then create sub-folder called Actionin the Applicationfolder.
  3. Again create a sub-folder called Helperin the Actionfolder.
  4. Now a create a file called AssetsList.phpin the plugin folder.

In the AssetsList.php folder, write the following code:

<?php
class Application_Action_Helper_AssetsList extends Zend_Controller_Action_Helper_Abstract {

    public function  direct() {
    }

    public function getList() {
        $module_dir = $this->getFrontController()->getControllerDirectory();
        $resources = array();

        foreach($module_dir as $dir=>$dirpath) {
            $diritem = new DirectoryIterator($dirpath);
            foreach($diritem as $item) {
                if($item->isFile()) {
                    if(strstr($item->getFilename(),'Controller.php')!=FALSE) {
                        include_once $dirpath.'/'.$item->getFilename();
                    }
                }
            }

            foreach(get_declared_classes() as $class){
                if(is_subclass_of($class, 'Zend_Controller_Action')) {
                    $functions = array();

                    foreach(get_class_methods($class) as $method) {
                        if(strstr($method, 'Action')!=false) {
                            array_push($functions,substr($method,0,strpos($method,"Action")));
                        }
                    }
                    $c = strtolower(substr($class,0,strpos($class,"Controller")));
                    $resources[$dir][$c] = $functions;
                }
            }
        }
        return $resources;
    }
}

To get the list, simply put the following line in any controller action:

$resources = $this->_helper->AssetsList->getList();

Hopefully, this helps out everyone. I will post the dynamic ACL plugin code in coming days when i am finished with it.

6 Comments more...

Working with ZendX_JQuery – Part 1

by on Aug.06, 2010, under Zend Framework

I have been real busy with work these days. So  i haven’t had the opportunity to write a lot on my blog. A few days back, i had to work on integrating Jquery in one of the Zend Framework applications. The task was to create an auto-complete textbox which shows you the country names when you type characters in it.

  • First download the latest version of the Zend Framework, Jquery and Jquery UI.     I downloaded the full version of the Zend Framework and Jquery UI.
  • Now create a new ZF application. I am assuming that you have correctly configured the Zend_Tool to create ZF applications.
  • Unzip the ZF archive file and copy the contents of extras/library folder into your application’s library folder.
  • Now in the application.ini file, write the following code to register the ZendX namespaces: autoloaderNamespaces[] = "ZendX"
  • Since i needed the functionality in only one controller, i didnt need to include it into bootstrap file. Open your controller file, and add the following line in the init() function:
    <?php $this->view->addHelperPath('ZendX/View/Helper/','ZendX_Jquery_View_Helper'); ?>
  • Now in your layout file, enter the following code to add ZendX_Jquery in the application by putting this code in the header section of the page:
    <?php echo $this->JQuery()
    ->setVersion('1.4.2')
    ->setUIVersion('1.8.2'); ?>
  • Write the following code into your controller’s view file:
    <form><?php echo $this->datePicker('pickdate','',array()); ?></form>
  • Now copy the file jquery-ui-[version]-custom.css in the jqueryui folder into your site.
  • Put the following code into the head section of your layout file:
    <?php echo $this->headLink()->appendStylesheet([PATH_TO_JQUERYUI_CSS]); ?>
  • Put the following javascript code in the page before the head section end tag:
    <script type="text/javascript">$(function(){
    $("#pickdate").datepicker(); });</script>
  • Now open your browser to view the page. This should now show a datepicker.

Thats it for part1 of my take on ZendX_Jquery. I havent completed the functionality of the autocomplete textbox using ZendX_Jquery. But i will post the part 2 of this post as soon as possible.

2 Comments more...

Adding Custom Decorators to Zend_Form in Zend Framework – Part 1

by on Jun.14, 2010, under Zend Framework

Hello Everyone!

I just started work on my Real Estate Management System (REMS). Its first form is a booking search form for properties available for rent. The form consisted of fields like location, start & end booking dates,  no.of bedrooms, price range etc. Typically any element defined inside a Zend_Form class is wrapped like this on a view file:

<dl id="ELEMENTID">ELEMENT LABEL</dl>
<dd>ELEMENT</dd>

I wanted to get rid of this default styling, so after reading the documentation i achieved it by writing this code in the init() function of my Zend_Form class after defining all the form elements:

$this->setElementDecorators(array('ViewHelper'));

I also converted my Login Form’s layout to a table-based also. Here is the code for that class:

<?php

class Form_Login extends Zend_Form {

public function init() {

$username = $this->createElement('text','username');
$username->setLabel('Username');
$username->setRequired(true);
$username->setAttrib('size','20');
$this->addElement($username);

$password = $this->createElement('password','password');
$password->setLabel('Password');
$password->setRequired(true);
$password->setAttrib('size','20');
$this->addElement($password);

$submit = $this->createElement('submit','submit',array('label'=>'Login'));
$this->addElement($submit);

// Code for Custom Decorators here ...
$username->setDecorators(array(
'ViewHelper',
'Errors',
array(array('data'=>'HtmlTag'), array('tag' =>'td','class' =>'element')),
array('Label',array('tag'=>'td')),
array(array('row'=>'HtmlTag'), array('tag'=>'tr')),
));

$password->setDecorators(array(
'ViewHelper',
'Errors',
array(array('data'=>'HtmlTag'), array('tag'=>'td', 'class'=>'element')),
array('Label', array('tag'=>'td')),
array(array('row'=>'HtmlTag'), array('tag'=>'tr')),
));

$submit->setDecorators(array(
'ViewHelper',
array(array('data'=>'HtmlTag'),array('tag'=>'td','class'=>'element')),
array('Label',array('tag'=>'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr')),
));

$this->setDecorators(array(
'FormElements',
array('HtmlTag',array('tag'=>'table')),
'Form',
));

}

}

?>

I hope this helps everyone out. Also checkout this great article Decorators with Zend_Form on Zend DEVZONE.

Leave a Comment more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!