Tuesday, December 27, 2011

PHP Zend Model Transactions, Rollback and commit

Add in the model

$db->beginTransaction();  try{       $model->insertSome($data1);       $model->insertAll($data2); //if this line cannot be run and the whole transaction should be rolled back.       $db->commit();  } catch (Exception $e) {       $db->rollBack();                                      echo $e->getMessage();}

 

PHP Zend Captcha

In Bootstrap

//generates an instance of Zend_Captcha //returns ID of captcha session public function generateCaptcha() { $captcha = new Zend_Captcha_Image(); $captcha->setTimeout('300') ->setWordLen('6') ->setHeight('70') ->setFont('/var/www/test/public/images/captcha/Harabara.ttf') ->setImgDir('/var/www/test/public/images/captcha'); $captcha->generate();    //command to generate session + create image return $captcha->getId();   //returns the ID given to session & image  }   //end function generateCaptcha   //validates captcha response function validateCaptcha($captcha) { $captchaId = $captcha['id']; $captchaInput = $captcha['input']; //$captchaSession = new Zend_Session_Namespace('Zend_Form_Captcha_' . $captchaId); $captchaSession = $_SESSION['Zend_Form_Captcha_' . $captchaId]; //$captchaIterator = $captchaSession->getIterator(); $captchaWord = $captchaSession['word']; if( $captchaWord ) { if( $captchaInput != $captchaWord ){ return false; } else { return true; } } else { return false; } }

In controller

$this->view->captchaId = $this->generateCaptcha();       //generates CAPTCHA image and session, returns session's ID if($this->getRequest()->isPost()){ $request = $this->getRequest(); $captcha = $request->getPost('captcha'); /*$cap_real_word = $_SESSION['Zend_Form_Captcha_'.$this->view- >captchaId]; if($cap_real_word != $captcha['input']){ echo "if a true value is sent, process form"; } else{ echo "captcha invalid, text doesn't match"; }*/ //print_r($captcha); exit;  if( isset($captcha) ) {       //if a post value is sent, process form if( $this->validateCaptcha($captcha) ) { $this->view->sub_resp = "success"; $captcha = $request->getPost('captcha'); } else { $this->view->sub_resp = "captcha invalid, text doesn't match"; } } }

In view

<img src="<?php echo $this->baseurl?>/images/captcha/<?=$this->captchaId ?>.png" alt="" /><br /> What's the word above say? <input class="required" name="captcha[input]" type="text" /> <input name="captcha[id]" type="hidden" value="<?=$this->captchaId ?>" />

PHP Zend Cache Using Memcache

Install memcached server, then memcache extension for corresponding php.

Configure Memcache In Bootstrap

protected function _initCacheManager() { $manager = new Zend_Cache_Manager(); $memcachedServers = array(); //Get memcached server details from db if(isset($this->_globalConfigs->site->memcachedservers)) { $memcacheConfigExists = true; $memcachedServers = explode(",", $this->_globalConfigs->site-  >memcachedservers); } $memcacheServerOptions = array(); foreach($memcachedServers as $memcachedServer) { $memcacheServerOptions[] = array( 'host' => $memcachedServer, //I have set the default values for now 'port' => 11211, 'persistent' => true, 'weight' => 1, 'timeout' => 5, 'retry_interval' => 15, 'status' => true, ); } $cacheBackEnd = array(); if (count($memcachedServers)) { $cacheBackEnd = array( 'name' => 'Memcached', 'options' => array( 'servers' => $memcacheServerOptions ) ); } else { //We fall back to file cache $cacheBackEnd = array( 'name' => 'File' ); } $dbCache = array( 'frontend' => array( 'name' => 'Core', 'options' => array( 'lifetime' => 7200, 'automatic_serialization' => true ) ), ''backend' => $cacheBackEnd ); $pageBlockCache = array( 'frontend' => array( 'name' => 'Output', 'options' => array( 'lifetime' => 7200, 'automatic_serialization' => true ) ), 'backend' => $cacheBackEnd ); $manager->setCacheTemplate('database', $dbCache); $manager->setCacheTemplate('pageBlock', $pageBlockCache); //test the cache is working $cache = $manager->getCache('database'); if(!$cache->save("WOWO LET ME GO TO CACHE", "testStre")) { throw new Zend_Exception("Unable to save to cache. Please check     memcached demon is running @ " . print_r($memcachedServers,true)); } $registry = Zend_Registry::getInstance(); $registry->set('cacheManager', $manager); //For caching db Metadata Zend_Db_Table::setDefaultMetadataCache($cache); }

Cache data e.g. In Index.phtml

$cacheManager = Zend_Registry::getInstance()->get("cacheManager"); $cache = $cacheManager->getCache("pageBlock"); if(!$result = urldecode($cache->load($this->session->cityNameEng))) { $cache->start($this->session->cityNameEng); {  /// content to be cached  } $cache->end(); } else{ echo $result; }

PHP Zend Cache

In Bootstrap

protected function _initCache() { $dir = ROOT_DIR; $frontendOptions = array( 'lifetime' => 7200, 'debug_header' => true, // for debugging 'regexps' => array( // cache the whole IndexController '^/$' => array('cache' => true), // cache the whole IndexController '^/index/' => array('cache' => true), ) );  $backendOptions = array( 'cache_dir' =>ROOT_DIR."/tmp" );  // getting a Zend_Cache_Frontend_Page object $cache = Zend_Cache::factory('Page', 'File', $frontendOptions, $backendOptions);  // $cache->remove('main'); //$cache->start('main');  Zend_Registry::set('cache', $cache); }

In controller / model / view

$cache = Zend_Registry::get('cache'); if(!$result = @urldecode($cache->load('mydata'))) { $cache->start('mydata'); { ////    content to be cached (in phtml) } $cache->save('mydata'); } else { Zend_Debug::dump($result); }

Difference between php 5.2 and 5.3

Basic and minor updates from 5.2 to 5.3

Backward Incompatible changes

  • clearstatcache() no longer clears the realpath cache by default.
  • realpath() is now fully platform-independent. Consequence of this is that invalid relative paths such as __FILE__ . "/../x" do not work anymore.
  • The array functions natsort()natcasesort()usort()uasort()uksort()array_flip(), and array_unique() no longer accept objects passed as arguments. To apply these functions to an object, cast the object to an array first.
  • The magic methods __get__set__isset__unset, and __call must always be public and can no longer be static. Method signatures are now enforced.

New Features

  • Support for jump labels (limited goto) has been added.
  • The ternary operator now has a shorthand form: ?:.
  • The HTTP stream wrapper now considers all status codes from 200 to 399 to be successful.
  • Exceptions can now be nested.
  • There are two new magic methods, __callStatic and __invoke.
  • It is now possible to use Heredocs to initialize static variables and class properties/constants.

Deprecated Functions