Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Friday, March 18, 2016

Twilio Voice call integration using PHP and JS


First step is to signup on twilio using a valid mobile number - which will get a verification code which is used to verify the mobile number.

Selection_120.png

www.twilio.com/try-twilio

On clicking the Get Your First Twilio Phone Number, a sample phone number will be provided by twilio which will be used to generate calls (From number).

Selection_121.png

Download the sdk and setup the code to autoload the sdk in the project.
Go to Dashboard www.twilio.com/user/account/voice/dashboard click on ‘view API credentials’ to get the id and token.

Now go to www.twilio.com/user/account/voice/dev-tools/twiml-apps and create a sample TwiML app. On the voice section provide an accessible url from which twilio will be fetching the from and to numbers for connecting (will explain in detail below).
E.g. http://DOMAIN/twilioCall.php

Generate required files for initiating calls.

demoCall.php : Display the dial-er page.

<?php
include 'Services/Twilio/Capability.php';
 
// put your Twilio API credentials here
// https://www.twilio.com/user/account/settings
$accountSid = 'AccountId';
$authToken  = 'token';
 
// put your Twilio Application Sid here
// https://www.twilio.com/user/account/voice/dev-tools/twiml-apps and select an app to get the app id
$appSid     = 'TwiMLAppID';
 
$capability = new Services_Twilio_Capability($accountSid, $authToken);
$capability->allowClientOutgoing($appSid);
$capability->allowClientIncoming('incommingTest');
$token = $capability->generateToken();
?>

<!DOCTYPE html>
<html>
  <head>
    <title>Call Demo</title>
    <script type="text/javascript"
      src="//media.twiliocdn.com/sdk/js/client/v1.3/twilio.min.js"></script>
    <script type="text/javascript"
      src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <link href="//static0.twilio.com/resources/quickstart/client.css"
      type="text/css" rel="stylesheet" />
    <script type="text/javascript">

      Twilio.Device.setup("<?php echo $token; ?>");

      Twilio.Device.ready(function (device) {
        $("#log").text("Ready");
      });

      Twilio.Device.error(function (error) {
        $("#log").text("Error: " + error.message);
      });

      Twilio.Device.connect(function (conn) {
        $("#log").text("Successfully established call");
      });

      Twilio.Device.disconnect(function (conn) {
        $("#log").text("Call ended");
      });

      Twilio.Device.incoming(function (conn) {
        $("#log").text("Incoming connection from " + conn.parameters.From);
        // accept the incoming connection and start two-way audio
        conn.accept();
      });

      function call() {
        // get the phone number to connect the call to
        params = {"PhoneNumber": $("#number").val()};
        Twilio.Device.connect(params);
      }

      function hangup() {
        Twilio.Device.disconnectAll();
      }
    </script>
  </head>
  <body>
    <button class="call" onclick="call();">
      Call
    </button>

    <button class="hangup" onclick="hangup();">
      Hangup
    </button>

    <input type="text" id="number" name="number" placeholder="Enter a phone number to call"/>
    <div id="log">Loading ...</div>
  </body>
</html>

twilioCall.php

<?php
header('Content-type: text/xml');
if (isset($_REQUEST['PhoneNumber'])) {
    $number = htmlspecialchars($_REQUEST['PhoneNumber']);
}?>

<Response>
    <Dial callerId="<?php echo $callerId ?>">
 <Number>"<?php echo $number ?>"</Number>
    </Dial>
</Response>

Key elements required for connection are Account SId, Token (www.twilio.com/user/account/settings) and appId (www.twilio.com/user/account/voice/dev-tools/twiml-apps and select an app to get the app id).

Now its ready to be tested. Note that since this is a demo account from and to numbers cannot be changed (From should be the number provided by Twilio during signup and to should be the verified number on the account).

Logs will be available over here : www.twilio.com/user/account/log/calls , on clicking the timestamp it will direct to the details of request and response.

www.twilio.com/user/account/monitor/alerts, this one provide alerts created during our test failures.

Selection_123.png

Alert logs
Selection_122.png

Wednesday, March 9, 2016

Sample application with AngularJS, PHP and Mysql

AngularJS sample application with PHP and MYSQL

Lets start by creating a sample database and a table to have some values which can be used for listing the data.

AngularJS PHP MYSQL



CREATE TABLE `movies` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `title` VARCHAR(255) NOT NULL, `director` VARCHAR(15) NOT NULL, `year` int(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=INNODB DEFAULT CHARSET=utf8;


Then some default entries to the table

INSERT INTO `movies` (`id`, `title`, `director`, `year`) VALUES (1, 'Mad Max: Fury Road', 'George Miller', '2015'), (2, 'Captain Phillips', 'Paul Greengrass', '2013'), (3, 'Room', 'Lenny Abrahamson', '2015') , (4, 'London Has Fallen', 'Babak Najafi', '2016') , (5, 'Deadpool', 'Tim Miller', '2016');


Now we have the database ready to be used, shall start from building the html pages, js and relative php file.

index.html

<!DOCTYPE html>

<html ng-app="customMovApp">

<head>

 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>

 <script type="text/javascript" src="js/app.js"></script>

</head>

        <body ng-controller="movieController">

                <div ng-include src=" 'views/movie.html' "></div>

        </body>

</html>

In angularjs based applications we use attribute names with ng keyword. As you can see in the html tag we have an attribute ng-app been set to a value 'customMovApp' and this is to initialize the html page with anuglarjs app which we will be defining on the app.js file. Within the body tag we have also initialized to controller to be used for this page with ng-controller attribute. Then we have a content loading div section which uses another view to be included when the index page is loaded. Here, note that the source url used within the ng-include attribute is enclosed within single quotes.

Now we shall define the app.js file which will be having the core of angular js application.

app.js

var app = angular.module('customMovApp',[]);

app.controller('movieController',  function($scope, $http) {

 getMovie();

 function getMovie() {

  $http.post("getMovie.php").success(function(data) {

   console.log(data);

   $scope.movies = data;

  });

 }

});


Here from the 1st line angular module is been initialized as 'customMovApp' and then with that we have created a new controller named 'movieController' and it has a function 'getMovie' which is in turn defined to call the php file getMovie.php and set the returned json object to 'movies' variable.

We already have a database and a table with some sample entries, we have the php script to connect to the database and returns the response as json object. For this we have a sample script which can be used.

getMovie.php

// mysqli connection object initialization
$mysqli = new mysqli('host', 'username', 'password', 'dbname');

$query = "select * from movies";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$arr     = array();

if($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
                $arr[] = $row;
        }

}

// JSON-encoded response
echo $json_response = json_encode($arr);


Now we need a view page to render the response from the controller action of angular module.

movie.html

<table ng-controller="movieController">

<thead><tr><th>Title</th><th>Director</th><th>Released Year</th></tr></thead>

<tbody>
 <tr ng-repeat="movie in movies">

 <td>{{movie.title}}</td>
 <td>{{movie.director}}</td>
 <td>
    <div ng-if="movie.year == '2016'"> <span>Current Year</span> </div>
 <div ng-if="movie.year != '2016'"> <span>{{movie.year}}</span> </div>
 </td>

 </tr>

</tbody> </table>

Here we are using ng-repeat to loop through all the movie records from the response object.

Thursday, July 9, 2015

Sugarcrm connection to mysql DB with SSL - Amazon RDS with SSL - using ca-cert file

This is based on Sugarcrm CE 6.5, and by default the MysqliManager.php doesnt support ssl connection to mysql db's, even if we set the 'ssl' flag on 'dboptions' of config.php file. To make the DBManager work, we need to update the MysqliManager code.

First, we need to have the ssl flag on and the file path to the ca-cert file, for that we can have these details on config_override.php
$sugar_config['dbconfigoption']['ssl'] = true;
$sugar_config['dbconfigoption']['ca_cert'] = '/home/user/ca-cert-rds.pem';

Then, update the MysqliManger.php file inside include/database folder.

            $link = FALSE;

            $configDbOptions = $this->getOptions();

            if ($configDbOptions['ssl'] === TRUE) {

                $this->database = mysqli_init();

                mysqli_options($this->database, MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, true);

                $this->database->ssl_set(NULL,NULL,$configDbOptions['ca_cert'],NULL,NULL);

                $link = $this->database->real_connect($dbhost, $configOptions['db_user_name'], $configOptions['db_password'], isset($configOptions['db_name'])?$configOptions['db_name']:'', $dbport, NULL, MYSQLI_CLIENT_SSL);

            } else {

                $this->database = mysqli_connect($dbhost,$configOptions['db_user_name'],$configOptions['db_password'],isset($configOptions['db_name'])?$configOptions['db_name']:'',$dbport);

                $link = TRUE;

            }



            if($link === FALSE) {

                $GLOBALS['log']->fatal("Could not connect to DB server ".$dbhost." as ".$configOptions['db_user_name'].". port " .$dbport . ": " . mysqli_connect_error());

                if($dieOnError) {

                    if(isset($GLOBALS['app_strings']['ERR_NO_DB'])) {

                        sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);

                    } else {

                        sugar_die("Could not connect to the database. Please refer to sugarcrm.log for details.");

                    }

                } else {

                    return false;

                }

            }

Friday, March 22, 2013

How to override an attribute name in yii model ?

In model add an override function for checking the errors generated on validation.

public function getErrors($attribute=null)
{
        $errors = parent::getErrors($attribute);
        if ($attribute == null) {
            // Ok We get a collection of errors
            if (isset($errors['attribute_to_be_replaces'])) {
                $error = $errors['attribute_to_be_replaces'];
                unset($errors['attribute_to_be_replaces']);
                $errors['replaced_attribute_name'] = $error;
            }
        }
        return $errors;
 }

Friday, March 2, 2012

PHP 5.4 Released Providing Built-in webserver

Key Features

  • New syntax like Traits.
  • <?= is now always available, regardless of the short_open_tag ini option
  • Class member access on instantiation has been added, e.g. (new Foo)->bar()
  • Class::{expr}() syntax is now supported.
  • The keyword 'insteadof' is introduced with PHP 5.4 (Traits)
  • Built-in webserver in CLI mode to simplify development workflows and testing
  • Cleaner code base (removal of multiple deprecated language features)

Traits :: mechanism for code reuse in single inheritance languages

Built-in webserver

Added for development purpose only. 

Start Webserver

# php -S localhost:8000

To get a specific document root use

# php -S localhost:8000 -t folder_name/

If a PHP file is given on the command line when the web server is started it is treated as a "router" script for the web server. The script is run at the start of each HTTP request. If this script returns FALSE, then the requested resource is returned as-is. Otherwise the script's output is returned to the browser.

 

 

Tuesday, January 10, 2012

Zend Pagination

Get the results in controller and assign to view.

Inside controller 


$users = $user->getAllUsers();
Zend_Paginator::setDefaultScrollingStyle('Sliding');
Zend_View_Helper_PaginationControl::setDefaultViewPartial(
'pagination_control.phtml'
);

$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Array($users));
$paginator->setView($this->view);

$page = $this->_getParam('page');
if( $page == null || $page == ""){
$page = 1;
}
$paginator->setItemCountPerPage(20);
$paginator->setCurrentPageNumber($page);
$this->view->paginator = $paginator;

Inside View


<?php echo $this->paginator; ?>
//Will render first, page numbers, and last anchor tags
<?php foreach ($this->paginator as $item): ?>
<input type="checkbox" />
<?php echo $item['name'] ?>
<?php echo $item['email'] ?>
<?php endforeach; ?>

Inside Pagination_controller.phtml

<?php if ($this->pageCount): ?>
<div class="pagination">
<?php if (isset($this->previous)): ?>
 
< a href="<?php echo $this->url(array('page' => $this->previous)); ?>" title="Previous Page">« Previous</a>"<?php else: ?>
<span class="disabled">« Previous</span>
<?php endif; ?>

<?php foreach ($this->pagesInRange as $page): ?>
<?php if ($page != $this->current): ?>
< a href="<?php echo $this->url(array('page' => $page)); ?>" class="number" title="1"> <?php echo $page; ?></a>
<?php else: ?>
<?php echo $page; ?>
<?php endif; ?>
<?php endforeach; ?>

<?php if (isset($this->next)): ?>
< a href="<?php echo $this->url(array('page' => $this->next)); ?>" title="Next Page">Next »</a>
<?php else: ?>
<span class="disabled">Next »</span>
<?php endif; ?>
</div>
<?php endif; ?>

Wednesday, January 4, 2012

Openshift with MySQL PHPMyAdmin

Click here to set up the Openshift server with Ubuntu.

Install Mysql for Openshift

/var/lib/gems/1.8/bin/rhc-ctl-app -a APPNAME -e add-mysql-5.1 -l EMAILID -p PASSWORD

Now Mysql is installed and access details will be obtained after running the above command.

Install PHPMyAdmin 

Download PHPMyadmin 

wget http://superb-dca2.dl.sourceforge.net/project/phpmyadmin/phpMyAdmin/3.4.8/phpMyAdmin-3.4.8-all-languages.zip

Go to application folder (local) and unzip the downloaded file

cd APP_FOLDER_NAME/phpunzip ../../phpMyAdmin-3.4.8-all-languages.zip

Rename the folder (name will be used to access the mysql [domainname/phpmyadmin_foldername])

mv phpMyAdmin-3.4.8-all-languages phpmyadmin

Update Configuration file for phpmyadmin

cd phpmyadmincp config.sample.inc.php config.inc.phpupdate config.inc.php$cfg['blowfish_secret']     = 'some value'; //COOKIE AUTH$cfg['Servers'][$i]['host'] = 'hostadress'; //host address obtained on mysql installation

Add files to be pushed to the server, and commit the changes

git add -Agit commit -m 'phpmyadmin setup'git push 

After pushing the changes to server, mysql can be accessed through
DOMAINNAME/phpmyadmin
e.g. http://sreejithblog-sreejithblog.rhcloud.com/phpmyadmin

Then login using the credentials obtained on MySql installation

Openshift with Ubuntu

Step 1 :: Install rubygems and openssh

sudo apt-get install git-core openssh-client ruby-full  sudo apt-get install rubygems1.8

Step 2 :: Install gems

sudo gem install --source http://gems.rubyforge.org --source https://openshift.redhat.com/app/repo/ rhc

Step 3 :: Create domain using RHC command

/var/lib/gems/1.8/bin/rhc-create-domain -n DOMAIN_NAME -l EMAILID -p PASSWORD

RHLogin is required
Domain name :: doesnt support non-alphanumeric characters
EMAILID :: registered login id for Redhat or Openshift which has express access
PASSWORD :: Login password 

Step 4 :: Create application ( with valid application type [raw-0.1, php-5.3, jbossas-7.0, rack-1.1, jenkins-1.4, perl-5.10, wsgi-3.2])

/var/lib/gems/1.8/bin/rhc-create-app -a APP_NAME -t php-5.3 -l EMAILID -p PASSWORD

Step 5 :: Repo folder will be created in the local machine also, now the application can be updated and commited to the server using git commands (git push).

Ref Adding Zend Application :: http://jango.posterous.com/deploying-zend-app-on-openshift

Tuesday, January 3, 2012

Zend Render a different Layout

You can add this in action controller.

$this->_helper->layout->setLayout('login');

Fire PHP DB profiler Zend

Add in bootstrap
 

$resource = $this->getPluginResource('db');                $db = $resource->getDbAdapter();                                    $profiler = new Zend_Db_Profiler_Firebug('All DB Queries');                $profiler->setEnabled(true);                $db->setProfiler($profiler);

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.