PHP
How to Develop a Template System in Zend Framework Application
by Raza 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:
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:
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
.
How to implement SSL in Zend Framework?
by Raza 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());
How to Export Categories/Subcategories from x-cart to Magento?
by Raza on Mar.21, 2011, under Magento
Hi guys!
I just started working in magento a few days back. One of the tasks was to import categories data from x-cart to magento. So lets get started:
- First create a file called func.export_magento.php in the folder include/func of the x-cart installation, and write the following code in it.
<?php if ( !defined('XCART_START') ) { header("Location: ../"); die("Access denied"); } function getSubCategoriesCSV($catid,$cattitle) { global $sql_tbl,$config; $strCSV = ''; $newline = "\n"; $categories = func_query("select * from $sql_tbl[categories] where parentid=$catid"); if(sizeof($categories)>0) { foreach($categories as $category) { $ctitle = '/'.$category["category"]; if(getSubCategoriesCSV($category["categoryid"],$cattitle)=='') { $strCSV .= '"default","'.$cattitle.$ctitle.'"'.$newline; } else { $strCSV .= '"default","'.$cattitle.$ctitle.'"'.$newline; $strCSV .= getSubCategoriesCSV($category["categoryid"],$cattitle.$ctitle).$newline; } } } return $strCSV; } ?> - Then create another file called export_magento.php in the admin folder of the x-cart installation. Write the following code in it:
<?php require "./auth.php"; require $xcart_dir."/include/security.php"; require $xcart_dir."/include/categories.php"; x_load("export_magento"); $newline = "\n"; $output = ''; $output .= '"store","categories"'; $output .= "$newline"; $parentCategories = func_query("select * from $sql_tbl[categories] where parentid=0 order by product_count desc;"); foreach($parentCategories as $pcat) { $output .= '"default","'.$pcat["category"].'"'; $output .= $newline; $csvstring = getSubCategoriesCSV($pcat["categoryid"],$pcat["category"]); $output .= $csvstring; $output .= $newline; } @mkdir($xcart_dir.'/export',0777,true); $expfile = $xcart_dir."/export/Categories.csv"; $fp = @fopen($expfile,'w+'); @fwrite($fp,$output); @fclose($fp); if(file_exists($expfile)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($expfile)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($expfile)); ob_clean(); flush(); readfile($expfile); exit; } $smarty->assign("main","magento"); # Assign the current location line $smarty->assign("location", $location); @include $xcart_dir."/modules/gold_display.php"; func_display("admin/home.tpl",$smarty); ?>The last four lines of code is for theme configuration and is for x-cart 4.1.8 gold. Change it accordingly for your version of x-cart.
- The above code will write the categories data into a CSV file, and will let you download the file.
- Before exporting the data to magento, you should install and configure magento on your system. Here is a guide that i previously wrote on installation in windows with xampp..
- When you have installed magento, login into the backend. Then goto System->Import/Export->Dataflow – Advanced Profiles. Click Add New Profile to add a profile.
- In the Profile Name textbox, write Import Categories. In the Actions XML textarea, write the following code:
<action type="dataflow/convert_adapter_io" method="load"> <var name="type">file</var> <var name="path">var/import</var> <var name="filename"><![CDATA[Categories.csv]]></var> <var name="format"><![CDATA[csv]]></var> </action> <action type="dataflow/convert_parser_csv" method="parse"> <var name="delimiter"><![CDATA[,]]></var> <var name="enclose"><![CDATA["]]></var> <var name="fieldnames">true</var> <var name="store"><![CDATA[0]]></var> <var name="number_of_records">1</var> <var name="decimal_separator"><![CDATA[.]]></var> <var name="adapter">catalog/convert_adapter_category</var> <var name="method">parse</var> </action>.
- Now click Save Profile to save the profile.
- Now upload the file into var/import folder of the magento installation.
- Now a create folder called MyApp in the app/code/local folder of magento installation. Create the following folders in the myappfolder also:
- Catalog/Model/Convert/Adapter/
- Catalog/etc/
- In the Catalog/Model/Convert/Adapter/ folder, create a file Category.php, and write the following code in it.
class MyApp_Catalog_Model_Convert_Adapter_Category extends Mage_Eav_Model_Convert_Adapter_Entity { protected $_categoryCache = array(); protected $_stores; /** * Category display modes */ protected $_displayModes = array( 'PRODUCTS', 'PAGE', 'PRODUCTS_AND_PAGE'); public function parse() { $batchModel = Mage::getSingleton('dataflow/batch'); /* @var $batchModel Mage_Dataflow_Model_Batch */ $batchImportModel = $batchModel->getBatchImportModel(); $importIds = $batchImportModel->getIdCollection(); foreach ($importIds as $importId) { //print '<pre>'.memory_get_usage().'</pre>'; $batchImportModel->load($importId); $importData = $batchImportModel->getBatchData(); $this->saveRow($importData); } } /** * Save category (import) * * @param array $importData * @throws Mage_Core_Exception * @return bool */ public function saveRow(array $importData) { if (empty($importData['store'])) { if (!is_null($this->getBatchParams('store'))) { $store = $this->getStoreById($this->getBatchParams('store')); } else { $message = Mage::helper('catalog')->__('Skip import row, required field "%s" not defined', 'store'); Mage::throwException($message); } } else { $store = $this->getStoreByCode($importData['store']); } if ($store === false) { $message = Mage::helper('catalog')->__('Skip import row, store "%s" field not exists', $importData['store']); Mage::throwException($message); } $rootId = $store->getRootCategoryId(); if (!$rootId) { return array(); } $rootPath = '1/'.$rootId; if (empty($this->_categoryCache[$store->getId()])) { $collection = Mage::getModel('catalog/category')->getCollection() ->setStore($store) ->addAttributeToSelect('name'); $collection->getSelect()->where("path like '".$rootPath."/%'"); foreach ($collection as $cat) { $pathArr = explode('/', $cat->getPath()); $namePath = ''; for ($i=2, $l=sizeof($pathArr); $i<$l; $i++) { $name = $collection->getItemById($pathArr[$i])->getName(); $namePath .= (empty($namePath) ? '' : '/').trim($name); } $cat->setNamePath($namePath); } $cache = array(); foreach ($collection as $cat) { $cache[strtolower($cat->getNamePath())] = $cat; $cat->unsNamePath(); } $this->_categoryCache[$store->getId()] = $cache; } $cache =& $this->_categoryCache[$store->getId()]; $importData['categories'] = preg_replace('#\s*/\s*#', '/', trim($importData['categories'])); if (!empty($cache[$importData['categories']])) { return true; } $path = $rootPath; $namePath = ''; $i = 1; $categories = explode('/', $importData['categories']); foreach ($categories as $catName) { $namePath .= (empty($namePath) ? '' : '/').strtolower($catName); if (empty($cache[$namePath])) { $dispMode = $this->_displayModes[2]; $cat = Mage::getModel('catalog/category') ->setStoreId($store->getId()) ->setPath($path) ->setName($catName) ->setIsActive(1) ->setIsAnchor(1) ->setDisplayMode($dispMode) ->save(); $cache[$namePath] = $cat; } $catId = $cache[$namePath]->getId(); $path .= '/'.$catId; $i++; } return true; } /** * Retrieve store object by code * * @param string $store * @return Mage_Core_Model_Store */ public function getStoreByCode($store) { $this->_initStores(); if (isset($this->_stores[$store])) { return $this->_stores[$store]; } return false; } public function getStoreById($id) { $this->_initStores(); /** * In single store mode all data should be saved as default */ if (Mage::app()->isSingleStoreMode()) { return Mage::app()->getStore(Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID); } if (isset($this->_storesIdCode[$id])) { return $this->getStoreByCode($this->_storesIdCode[$id]); } return false; } /** * Init stores * * @param none * @return void */ protected function _initStores () { if (is_null($this->_stores)) { $this->_stores = Mage::app()->getStores(true, true); foreach ($this->_stores as $code => $store) { $this->_storesIdCode[$store->getId()] = $code; } } } } ?>Also copy this file into app/code/core/Mage/Catalog/Model/Convert/Parser/ folder.
- Create a file config.xml in the MyApp/Catalog/etc/ folder. Write the following code in it:
<?xml version="1.0" encoding="UTF-8"?> <config> <global> <models> <catalog> <rewrite> <convert_adapter_category>MyApp_Catalog_Model_Convert_Adapter_Category</convert_adapter_category> </rewrite> </catalog> </models> </global> </config> - Now create another file MyApp_All.xml in the app/etc/modules folder,and write the following code in it.
<?xml version="1.0"?> <config> <modules> <MyApp_Catalog> <codePool>local</codePool> <active>true</active> </MyApp_Catalog> </modules> </config> - Now goto System->Import/Export->Dataflow – Advanced Profiles. Click on the profile you just created in step 6. Click Run Profile. Now click Run Profile in Popup. This will open a popup window, which will start importing the categories data into magento from the CSV file you downloaded from the x-cart script in step 1 & 2.
- In case of any issues, please dont hestitate to comment…
How to properly automate a MySQL database with triggers and stored procedure
by Raza on Jan.28, 2011, under PHP
Hi guys!
I would like to share with you this great article on implementing stored procedures with triggers …
http://suite101.com/article/mysql-stored-procedures-and-triggers-a71091
Get list of all modules with all controllers and actions in Zend Framework
by Raza 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:
- Create a folder called Application in your site’s library folder.
- Then create sub-folder called Actionin the Applicationfolder.
- Again create a sub-folder called Helperin the Actionfolder.
- 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.
How to create Filefield Entries in Drupal?
by Raza on Jan.06, 2011, under Drupal
Hey guys! I wrote a tutorial on how to programmatically create nodes in Drupal. In this tutorial, i will show you how to write FileField entries using a Drupal module.
function YOURMODULE_CALLBACK() {
$arrfiles = return filePaths(YOUR_IMAGES_DIRPATH);
$filesinfo = array();
foreach($arrfiles as $file) {
$fn = basename($file);
//copying from source folder to drupal's sites/default/files
$cp = copy($file,'/sites/default/files'.$fn);
if($cp) {
$files = new stdClass();
$files->filename = basename($file);
$files->filepath = 'sites/default/files'.$fn;
$files->filemime = file_get_mimetype(basename($file));
$files->filesize = filesize($file);
$files->uid = 1;
$files->status = FILE_STATUS_PERMANENT;
$files->timestamp = time();
drupal_write_record('files', $files);
$filesinfo[] = array(
'fid' => $files->fid,
'title' => basename($files->filename),
'filename' => $files->filename,
'filepath' => $files->filepath,
'filesize' => $files->filesize,
'mimetype' => file_get_mimetype(basename($file)),
'description' => basename($file),
'list' => 1,
);
}
}
$node = node_load(NODEID);
$node->field_images = $filesinfo;
node_save($node);
}
function filePaths($path) {
$dir = new DirectoryIterator($path);
$filelist = array();
foreach($dir as $file) {
if($file->isFile()) {
$filelist[] = $file->getFilename();
}
if($file->isDir()) {
filePaths($file->getPath());
}
}
return $filelist;
}
How to programmatically add nodes in Drupal?
by Raza on Dec.20, 2010, under Drupal
Hi guys! I haven’t posted anything new on my blog for a long time. Because i have been really busy with work. Currently i am working on drupal, and the project is about creating a villa rentals and sales website. One of the tasks was to import the current client database information into the Drupal CMS. The database had all the rates information in the properties table and all different features for the properties like amenities, location, property type etc were stored in separate tables. To do that, i first created all the vocabularies and taxonomies in the drupal backend to mirror to original features data for properties and then i simply created a new folder called propertydata_import in my sites/all/modules folder. The code for the file is:
; $Id$ name = "Import Properties Data" description = "Import Properties Data" core = 6.x package = "MYSITE"
Now create another file called propertydata_import.module and do the following. I have the whole procedure below in a series of steps and it is important that you follow the order.
<?php
function propertydata_import_help($path, $arg) {
switch ($path) {
case "admin/help/propertydata_import":
$output = '
' . t("Import Property Data into Drupal") . '
';
break;
}
return $output;
}
function propertydata_import_perm() {
return array('administer propertydata_import', 'access propertydata_import content');
}
function propertydata_import_menu() {
$items = array();
//Link to the propertydata_import admin page:
$items['admin/propertydata_import'] = array(
'title' => 'Import Property Data into Drupal',
'description' => 'Import Property Data into Drupal',
'page callback' => 'propertydata_import_callback',
'access arguments' => array('administer propertydata_import'),
'type' => MENU_NORMAL_ITEM,
);
return $items;
}
function propertydata_import_callback() {
$conn = mysql_connect('localhost','YOUR_MYSQL_USER','YOUR_MYSQL_USER_PASSWORD');
if($conn) {
mysql_select_db('YOUR_MYSQL_DATABASE',$conn);
}
$properties = mysql_query("select * from properties;");
while($property=mysql_fetch_assoc($properties)) {
$node = new StdClass();
$node->type = 'property';
$node->status = 1; // Set to 0 if you do not want the content published
$node->promote = 0; // Set to 1 if you do not want the content promoted to the front page
$node->sticky = 0; // Set to 1 if you do not want the content sticky
$node->title = $property["title"];
$node->body = $property["description"];
$node->teaser = $property["description"];
$node->format = 2;
$node->language = '';
/*
Refer to other fields in the results by seeing the content type contemplate variables by clicking http://anguillaluxurycollection.com/admin/content/types/templates and select your relevant content type template. Suppose your content type is 'Property'. To see its contemplate settings, click the 'Edit Template' link to view the content type variables for Body ...
You can enter taxonomy using:
$node->taxonomy[] = array();
*/
$node = $node_submit($node);
if($node) {
node_save($node);
$nid = $node->nid;
$vid = $node->vid;
// Publish the node to the default domain ...
db_query("insert into domain_access(nid,gid,realm) values($nid,0,'domain_id');");
}
}
}
Working with ZendX_JQuery – Part 1
by Raza 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.
Working with Time Zones in PHP
by srmklive on Jun.19, 2010, under PHP
A few days ago at work, one of my colleagues had a task to display three digital clock in PHP for Barbados, Los Angeles and London. He asked for my help, and i kind of started working on how to do this. I obviously chose jquery to handle all the JS stuff for me. Here is what i did:
First for getting the timezones for specified locations, i created a PHP file ‘setTimes.php’, containing the following code:
$timezones = DateTimeZone::listAbbreviations();
/*
// Using This Code i found out the timezones the specified locations are using ..
$tzkeys = array_keys($timezones);
foreach($tzkeys as $tzk) {
$tzone = $timezones[$tzk];
for($i=0;$i<sizeof($tzone);$i++) {
$tzitem = $tzone[$i];
foreach($tzitem as $tzi)
echo "$tzi<br />";
echo "<p></p>";
}
}
*/
$londontime = $timezones['bdst'][0];
$usptime = $timezones['pdt'][0];
$barbtime = $timezones['bmt'][0];
$tzid = array($londontime["timezone_id"],$usptime["timezone_id"],$barbtime["timezone_id"]);
$timevalues = "";
foreach($tzid as $tz) {
date_default_timezone_set($tz);
$timevalues.= date("h:i:s A").'___';
}
echo json_encode(array($timevalues));
Now lets look at the code line by line:
$timezones = DateTimeZone::listAbbreviations();
This will store all the PHP supported timezone information in an array… Now look at the commented code and find out your specific timezone valus. I simply searched for the relevant timezones and stored their ids in the code below:
$londontime = $timezones['bdst'][0]; $usptime = $timezones['pdt'][0]; $barbtime = $timezones['bmt'][0];
Then i simply store the above values in an array, and then iterate through each value to get the current time in that timezone. After i simply encode the values in JSON using PHP’s native json_encode
$tzid = array($londontime["timezone_id"],$usptime["timezone_id"],$barbtime["timezone_id"]);
$timevalues = "";
foreach($tzid as $tz) {
date_default_timezone_set($tz);
$timevalues.= date("h:i:s A").'___';
}
echo json_encode(array($timevalues));
Now create a file index.php and add the following code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Digital Clocks in PHP</title> <script type="text/javascript" src="jquery-1.4.2.min.js"></script> <script type="text/javascript" src="script.js"></script> </head> <body onload="startclocks()"> <p>London Time: <span id="londontime"></span></p> <p>US Pacific Time: <span id="usptime"></span></p> <p>Barbados Time: <span id="barbtime"></span></p> <a href="#" onclick="stopclocks()">Stop All Clocks</a> </body> </html>
In the script.js, enter the following code:
var clockvalues = null;
var clocksrunning = false;
function stopclocks() {
if(clocksrunning) {
clearTimeout(clockvalues);
clocksrunning = false;
}
}
function showclocks() {
$.ajax({
url: '/tztest/setTimes.php',
success: function(data) {
var timevals = data.split("___");
timevals[0] = timevals[0].substr(2);
//alert(timevals[0]+" "+timevals[1]+" "+timevals[2]);
$("#londontime").html(timevals[0]);
$("#usptime").html(timevals[1]);
$("#barbtime").html(timevals[2]);
}
});
clockvalues = setTimeout("showclocks()",1000);
clocksrunning = true;
}
function startclocks() {
stopclocks();
showclocks();
}
I think the code itself is self-explanatory. So no need to explain that i believe …
. Dont forget to download the Sample Code too. Happy coding ..
Adding Custom Decorators to Zend_Form in Zend Framework – Part 1
by Raza 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.

