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

Wednesday, July 13, 2011

Is PHP complied ?

PHP is compiled at run time. The external PHP compliers merely cleans up the code to make it compile faster.
But it is always complied at run time; ie, when a user accesses the webpage.

PHC is an open source compiler for PHP with support for plugins. In addition, it can be used to pretty-print or obfuscate
PHP code, as a framework for developing applications that process PHP scripts, or to convert PHP into XML and back,
enabling processing of PHP scripts using XML tools.

ref : http://www.phpcompiler.org/

 

Tuesday, June 28, 2011

PHP OOPs concepts

Access control modifiers 
Public:  used from anywhere in the script  Private:  only be used by the object it is part of; it cannot be accessed elsewhere  Protected:   used by the object it is part of, or descendants of that class   Final:  This variable or function cannot be overridden in inherited class/es Abstract:   This function or class  cannot be used directly - you must inherit from them first
Interfaces
Object interfaces allow you to create code which specifies which methods a class  must implement, without having to define how these methods are handled.
<?php    // Declare the interface 'iTemplate'  interface iTemplate  {  public function setVariable($name, $var);  public function getHtml($template);  }    // Implement the interface  // This will work  class  Template implements iTemplate  {  private $vars = array();    public function setVariable($name, $var)  {  $this  --->vars[$name] = $var;  }    public function getHtml($template)  {  foreach($this->vars as $name => $value) {  $template = str_replace('{' . $name . '}', $value, $template);  }    return $template;  }  }    // This will not work  // Fatal error: Class BadTemplate contains 1 abstract methods  // and must therefore be declared abstract (iTemplate::getHtml)  class  BadTemplate implements iTemplate  {  private $vars = array();    public function setVariable($name, $var)  {  $this->vars[$name] = $var;  }  }  ?>
Encapsulation
<?php    class  Hide {  private $myname;  function getmyname()  {  $myname = "damodharan";  return $myname;  }  }  class  damu {  private static $name;  public function name()  {  if( $this->name == null ) {  $this->name = new Hide();  }  return $this->name;  }  }  $run = new damu();  echo $run->name()->getmyname();  ?>
Polymorphism
<?php    class  Base  {  function mytext()  {  echo "hi am from base class ";  }  }    class  myFirstClass extends Base  {  function mytext()  {  echo "hi am from myFirstClass class ";  }  }  class  mySecondClass extends Base  {  function mytext()  {  echo "hi am from mySecondClass class ";  }  }  //create the object for the class using Polymorphism   $objects = array ( $baseIns = new Base(), $myFirstClasIns = new myFirstClass(), $mySecondClasIns = new mySecondClass()  );    foreach ($objects as $object) {  echo $object->mytext();  echo " \n";  ?>

Thursday, April 28, 2011

Sonar for PHP code coverage

Sonar is quality management platform, checking code quality based on certain rules and custom rules.

Sonar runs on java so requires JDK v1.5 or later.

After that download latest version of sonar from http://www.sonarsource.org/downloads/ 

Starting sonar server

[PATH_TO_SONAR]/bin/[OS]/sonar.sh console

e.g.

/usr/local/sonar/linux-x86-32/sonar.sh console/start

Now the sonar has been started at http://localhost:9000 by default, config details of sonar can be updated
at sonar.properties inside conf.

For running php code coverage

Sonar is basically used for Java projects which can be extended for php using maven plugin.
So download latest maven from http://maven.apache.org/download.html

 

Now for adding project to sonar pom.xml file has to be created in the root folder of the project.

<?xml version="1.0"?> <project > <modelVersion>1.0.0</modelVersion> <groupId>Group_name</groupId> <artifactId>name</artifactId> <name>Project</name> <version>1.0</version> <packaging>pom</packaging> <build> <directory>build</directory> <sourceDirectory>application</sourceDirectory> <testSourceDirectory>tests</testSourceDirectory> </build> <properties> <sonar.language>php</sonar.language> </properties> </project>

 

For running php code coverage it requires phpunit to be configured.
Then coverage report is created using phpunit.

e.g.

phpunit --coverage-clover build/logs/phpunit.coverage.xml --log-junit build/logs/phpunit.xml

According to the pom.xml file the reports are created inside build/logs folder.

Some of the additional plugins are required for maven to run for PHP.

 

  1. Install PHP runtime with the corresponding xdebug extensions. Version 5.2.6 or newer is required.
  2. Install PEAR. Version 1.8.0 or newer is required
  3. Install PHPUnit version 3.5.5 (strictly)
  4. Install phpcpd version 1.3.0 (strictly)
  5. Install PHPDepend PHPMD version 0.2.5
  6. Install PHP_CodeSniffer version 1.3.0

After running PHPUnit, it ready for sonar to run with maven from project root folder.

[PATH_TO_MAVEN]/bin/mvn sonar:sonar

with -e option it lists the trace errors. After Build is success the web is updated with the new build reports. 

 

Wednesday, April 27, 2011

Thursday, April 21, 2011

Twitter updates via RSS using PHP

$rssUrl = "http://twitter.com/statuses/user_timeline/USERNAME.rss"; $rss = @file_get_contents($rssUrl); if($rss){ $xml = @simplexml_load_string($rss); if($xml !== false){ foreach($xml->channel->item as $tweet){ echo $tweet->pubDate."\n"; echo substr($tweet->description,10)."\n\n"; } }else{         echo "Error: RSS not valid"; } }else{ echo "Error: Cant load RSS"; }

Just replace the username with the required one.

Tips to make php better

Write Clean Logic Statements
unclean code

if($userLoggedIn) { // Hundreds of lines of code }else{ exit(); }

clean code

if(!$userLoggedIn) { exit();  }  // Hundreds of lines of code


Use Less PHP And More HTML With Alternative Syntax
 

Use "sprintf" and Friends

uncleanly spliced code

$sql = "SELECT col1, col2, col3 FROM people WHERE first_name = '" . mysql_real_escape_string($first_name) . "' AND last_name = '" . mysql_real_escape_string($last_name) . "'AND foo = '" . ($bar = "good" ? "good" : "bad") . "' ORDER BY col1" ;

cleanly assembled string with sprintf

$sql = 'SELECT col1, col2, col3 ' . 'FROM people ' . 'WHERE first_name = "%s" ' . 'AND last_name = "%s" ' . 'AND foo = "%s" ' . 'ORDER BY col1 ';  $sql = sprintf($sql, mysql_real_escape_string($first_name), mysql_real_escape_string($last_name), ($bar = "good" ? "good" : "bad"));

Wednesday, April 6, 2011

GIT Committing to a different remote branch

From master

git branch -a

gives the list of all remote branches


Create remote branch in local and get all the updates from the corresponding branch

git branch -t branch_name(same as in server) origin/branch_name

git checkout branch branch_name

make changes

commit ur code

then 

git pull origin branch_name

git push origin branch_name

Friday, March 18, 2011

GIT repository

Setting up GIT in Linux

Step 1 : Add user account in github.com

Step 2 : Install GIT and GIT GUI in your machine.

Step 3 : Then open the terminal and type git gui, a popup window will come.
             From that select Help -> Show SSH Key, copy the key and add it to your GITHUB account.

Step 4 : There are 2 types of repositories in GITHUB
             1. Public
             2. Private
             In your dashboard Repositories will be listed.

Step 5 : Select a repository
             There will be SSH url copy that and go to your machines web folder in your machine through
             Terminal where you want to create a copy of the project.

Step 6 : Then type  :  git clone {sshurl} here ssh url is the url copied from the GITHUB Repository.

Step 7 : When this command is executed the clone from the repository is generated in your local machine.
            Then browse to the project folder.

Step 8 : If you want to create a branch (i.e. view)  in your machine which will not affect the MASTER (i.e. copy of the project from server)
            use git branch branch_name will create a new branch. Then use git checkout branch_name will checkout into the branch.
            Now you can work on your own branch.

Step 9 : After working on your branch, if you need to add some of your changes to the git repository use git gui command inside your project folder.
            A popup comes with 3 frames. Left most one will be the files that has been changed based on the master copy.
            On selecting the file it shows the changes that you have made on the file based on the Master copy on the right side frame(biggest).
            On the right side there are 2 sections : one is the files that are been changed. On double clicking on the files it will move to the staged section
            i.e. files to be merged with the master copy. Then on the right side bottom there is section for specifying your comment on the updation.
            After adding the comment press the commit button. Before merging the files into the master copy you have to stack (buffer) the changes that
            you have made for other files which are not to be merged to the master copy.

Step 10 : use git stash to stack your local changes then checkout to your master copy using git checkout master. Then take all the updates from server
            using git pull. Then merge the updates that you have committed to the master copy using git merge branch_name.
            Now you have made the changes to the master and can be pushed to the github repository by using git push

Step 11 : Then is you need your local changes to be applied back, checkout to your branch using git checkout branch_name,
            now you have to apply the updates obtained from the github repository by git rebase master (which resets your branch to the master copy).
            Now you need to apply your local changes which has been stacked before merging, by git stash pop, again you can work separately on your local copy.

Zend assigning clean values

Assigning clean values

 

$entityFilter = new Zend_Filter_HtmlEntities();
$urlFilter = new My_Filter_Url();
$this->view->title = $this->escape("Seite 1");
$this->view->headline = $entitiyFilter->filter($this->getRequest()->getPost('link'));
$this->view->link = $urlFilter->filter($this->getRequest()->getPost('link'));

Monday, March 7, 2011

Jquery Validation Check for username with letters, numbers and dashes

$(function () {  $.validator.addMethod("nameRegex", function(value, element) { return this.optional(element) || /^[a-z0-9\ \'-]+$/i.test(value); // letters, digits,',- and space. }, "No special characters please.");  $("#signupForm").validate({ rules: { "login": { required: true, loginRegex: true, } } }); });

 

Using Zend Auth Adapter for login

Add this in your action controller

$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter()); $authAdapter->setTableName('users'); $authAdapter->setIdentityColumn('Email'); $authAdapter->setCredentialColumn('Password'); $authAdapter->setIdentity($email); $authAdapter->setCredential($password);  $auth = Zend_Auth::getInstance(); $result = $auth->authenticate($authAdapter); if (!$result->isValid()) { $auth->clearIdentity(); return 'Oops check your password or maybe you havent confirmed your email or forgotten your password. Click here to resend~1'; }

 

Thursday, February 24, 2011

Zend PHP Redirect from anywhere

$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector'); $redirector->gotoUrl('/redirect/path');

 

Jquery onfocus for textfield default value

var default_value = "default data"; $('.class').focus(function() { if(this.value == default_value) { this.value = ''; } }); $(.class).blur(function() { if(this.value == '') { this.value = default_value; } });

 

Zend Render a different view script path

You can add this in any processing function.

$view = new Zend_View(); $view->addScriptPath("script/path"); $view->data = $data; // assign data to view $view->render('script_file_name'); // e.g. test.phtml

Note : if the view is not rendered then use exit at the last line of the view script file.

Tuesday, February 22, 2011

Zend mail

   $mail = new Zend_Mail ();
   $mail->setFrom('from_email_id', 'From Name');
   $mail->addTo('to_email_id', 'Recipient Name');
   $mail->setSubject('Email subject');
   $mail->setBodyText('Email content');
   $mail->send();

Getting duplicate entries and their count

For getting the duplicates you can use HAVING and GROUP BY functions in mysql


SELECT COUNT(*) AS num_entries, Email FROM subscribers GROUP BY Email HAVING num_entries > 1