jump to navigation

How to Install Git 1.9.0 on CentOS 6.4 (Compiling from Source) March 24, 2014

Posted by Tournas Dimitrios in Uncategorized.
add a comment

CentOS_logoGit is an open source, distributed version control system developed by Linus Torvalds , the creator of the Linux kernel  . Git allows a team of people to work together, all using a copy of files from a central repository , and when they have made their own contribution on the code , committing the changes back to the central repository . This helps the team cope with the confusion that tends to happen when multiple people are editing the same files . A characteristic example where Git is used for , is the Linux kernel , with 3500 contributors and 15 million lines of code . Although Git is an excellent tool for managing large , complex projects with tens or even hundreds contributors , it can also be used on small projects with one developer or a small team . This flexibility makes it a great choice for implementing version and source control for software projects of any size .
There are countless  Git client tools on the market  , GUI or terminal based , commercial or free . Without doubt , the most adopted client tool for Git is  terminal based (which happen to be named “git”) . Two reasons that made this tool the primary choice by the majority of the software development community  are flexibility and cross-platform compatibility . Software developers that use the Windows platform are lucky here , they just download the latest version of the git-client and run the installation script (an “.exe” file) . In contrast , software developers that have chosen a *nix like platform for their development are “trapped” to use a version of  git that their official repository provides . And usually , the officially supported repositories linger to adopt the latest version of the tools they support . That might sound unimportant at first , and usually it is  . But there are cases where a newer version of a “package” has a feature that we really need . The official supported repository of  CentOs 6.4 provides a “git” version that is quite a bit outdated .While many developers use only git’s basic functionality  and don’t care about the officially provided version , others though , have the need to use all available features that this tool provides  .

Probably you could compile even newer version of git from the source . However, the purpose of this article is to show how to install the latest stable version of git available in the repositories . We won’t need to remove the officially supported git client from our machine , as both versions can coexist on the same box and used interchangeably . To compile the source code (which won’t take more than five minutes) , we must have the following tools pre-installed on our machine : lib-curl-devel , expat-devel , openssl-devel , zlib-devel and gcc . Here are the steps to follow :

  • open a terminal
  • yum list installed |egrep -wi ‘libcurl-devel|expat-devel|openssl-devel|zlib-devel|gcc’ #verify that the required tools are installed
  • cd /tmp
  • mkdir  git ; cd git
  • wget https://www.kernel.org/pub/software/scm/git/git-1.9.0.tar.gz

  • tar xzfv git-1.9.0.tar.gz
  • cd git-1.9.0/
  • sudo make prefix=/usr/local all
  • sudo make prefix=/usr/local install
  • cd ../.. ; rm -fR git
  • # now restart your terminal
  • which git  # /usr/local/bin/git
  • git  –version #git version 1.9.0
  • /usr/bin/git  –version  #git version 1.7.1

Both versions are now installed on our machine . The compiled version is installed on /usr/local/bin directory  and the version of the officially supported repository was installed on /usr/bin directory . Because /usr/local/bin has precedence in terminal’s $PATH variable , this version of git will be used as default . We can “force” the terminal to use  the git version installed by our officially supported repository by explicitly calling the tool (/usr/bin/git)  .  The steps followed on my terminal while compiling/installing git were recorded and can be viewed on showterm.io .
Happy coding , keep yourself healthy and don’t hesitate to drop a message on the comment section below .

Advertisements

Webinar Registration : “development lifecycle with Git” February 19, 2014

Posted by Tournas Dimitrios in Uncategorized.
add a comment

If you already have a basic knowledge of Git version control , don’t miss this webinar . I’m sure , it will be a high level presentation as the seminar is organized by the technical stuff of Atlassian .  An excerpt from the registration page : 

If you’ve ever sat down with a more experienced developer for a pair programming session, you’d probably agree that it’s one of the most effective ways to learn, and absorb new skills, tools, and tricks. So I am very happy to present you with a new webinar that will reproduce the same feel of a live training session. This is your chance to sit beside me as I work through a typical bug-fix lifecycle from branch creation, through code review, to the final merge, using the powerful toolset that Git brings to every developer. 

Registration is limited to a thousand live participants, so reserve your spot today . I made an registration  and hope to see you there too . 

A Quick Overview of Eloquent’s (Laravel) Mass-assignment Protection May 14, 2013

Posted by Tournas Dimitrios in PHP.
8 comments

Laravel’s  ORM (Eloquent) provides a beautiful , simple Active-Record implementation for working with your database . Each database table has a corresponding “Model_Class” which is used to interact with that table . As I’m aware off , many [all] ORM’s had the ability to mass-assign properties directly into the database , which is a   security vulnerability . Mass assignment is something most programmers make use of as it provides an easy (convenient) way to populate the properties of a model object from a form . Unfortunately its simplicity can make it a target for hackers , a submitted form can easily be forged just by using a CLI-tool (CURL) or by using a browser plugin (Firefox’s Firebug) to pass POST parameters to a page . The way to stop this kind of attack is by limiting the attributes that can be set from the form (or from a POST method) .

Basics first :

Active-Record is designed upon the principles of the “Active-Record” design pattern , which was first described by Martin Fowler . The Active -Record pattern has been implemented in many forms across  all  programming languages , the basic concepts remain the same though . A database table is mapped into  a Class (the Model in a MVC paradigm) , and each instance of that Class represents a table row . The tables and rows of the database are abstracted into native PHP objects . This allows the programmer to focus more on manipulating the data and less on writing SQL queries . The following lines of code are just a representation  of what I’m talking about , it’s evident that the code hides (abstracts) the database query language (SQL) .

// Get all records from Users table
$users = User::all() ;
// How many records of the Users table has been voted more than 100 times
$count = User::where('votes', '>', 100)->count();
//  Updating a record into Users table
User::where('username', '=', 'user3')->update(array('password' =>  Hash::make('John123')));

To keep things concentrated , most Frameworks apply the “Convention Over Configuration” paradigm  . In our Active Record implementation ,  a User Model Class maps to a Users Database-table (notice the plural and singular expression) . This default convention can be explicitly overwritten though .

Back on track : 

Let’s recap : a Class that implements the Active-Record design pattern is used to interact with our database-tables . All we have to do is  using CRUD operations on an Object that was previously instantiated from the aforementioned  Class  , neglecting the underlying SQL logic . And you might wonder , where is the vulnerability that we talked about at the beginning of this article  . Well let’s be honest , we’re almost always lazy programmers  and prefer to write less code (yes I’m cheating here , assuming that all programmers behave like me ) . Our laziness establishes an assured “achilles heel” into  application’s foundations . Sooner or later a “black hat guy” will discover our application’s vulnerability and most likely he will try to  occupy administrator privileges . In such a scenario , the consequences are evident , I don’t even want to think about it .
A couple years ago (early in 2012 ) , a Russian developer named Homakov , discovered the “Mass Assignment” vulnerability into Github’s website and used this “security hole”  to gain commit access . Github’s web-app was build on Rails , but as aforementioned previously , the concepts remain the same , no matter which programming language is used to implement an Active Record design pattern . Don’t fear , the flaw has since been fixed in Rail’s  and Eloquent (Laravel’s Active Record implementation) , and I’m sure that other ORMs have taken their precautions to .
Do you remember my aforementioned “Convention Over Configuration” paradigm ? This also applies into this situation , the default “set-up” in Laravel’s and Rail’s Active Record implementation is to suspend “mass assignment” functionality , it can be overwritten though .  This restriction protects our application , in case a programmer  skipped to apply basic security practices . There are situations that we don’t need this “strict security model” though ( for instance : during prototyping or development cycle of our application ) .
A practical example will illustrate what this article is trying to describe . First , the code-example shows how mass assignment was done until the restrictions were applied ( after Homakov’s discovery)  .

<?php

class UserController extends BaseController
{

	public function save()
	{
		$user = new User(Input::all()) ;
		$user->save()  ;
		// Do other stuff here
	}

}

In the above code , all form submitted fields were inserted into the database-table (mass assignment ) . It’s not shown here , but the code took all precautions to protect our application against SQL-injection , Cross-Site-Scripting XSS and Cross-Site-Request-Forgery CSRF . Mass assignment wasn’t restricted , an hacker had to guess how the database-table indicated an administrator / logged-in user (perhaps a column with a name of : is_loggedIn , is_admin ) . Last step of attacker’s journey was to submit a forged form which contained those column fields into the submitted data and boooom , he gained free access to the web-app .

The following code demonstrates how we could protect our app against the mass assignment vulnerability :

<?php

class UserController extends BaseController
{

	public function save()
	{
		$user = new User() ;
		$user->email = Input::get('name');
		$user->pnone = Input::get('phone');
		$user->name = Input::get('name');
		$user->save()  ;
		// Do other stuff here
	}

}

The code above demonstrates the right way to store submitted form data  . We allow only specific field to be stored into the database table .
As aforementioned , by default , mass assignment is disabled in Laravel , we can loosen or disable this restriction though . In Laravel 4 two properties can configure Model’s behavior ($fillable and $guarded ) .

<?php
class User extends Eloquent {
/*
In this example , only the three listed attributes will be mass-assignable.
*/
    protected $fillable = array('first_name', 'last_name', 'email');

}

class User extends Eloquent {
/*
In the example , the id and password attributes may not be mass assigned
*/
    protected $guarded = array('id', 'password');
/*
Or blocking all attributes from Mass Assignment
*/
	protected $guarded = array('*');

}

Happy coding .

Boosting the Performance of a PHP-project with an Autoload Class Map April 15, 2013

Posted by Tournas Dimitrios in PHP.
1 comment so far

The de facto standard for developing PHP applications is the OOP – model , it’s the most adopted programming paradigm in today’s software design . For organizational reasons , each Class (or Interface)  is defined in its own file . Those files are then stored into a tree-like hierarchical structure . An OOP project is build by instantiating Objects  from those aforementioned Classes ( imagine Classes as blueprints with predefined functionality) . Before a Class can be used (as a blueprint) into our project ,  it has to be imported first (PHP has four “tools” for importing Classes , require , require_once , include  and include_once) . PHP 5 introduced the magic function __autoload() which is automatically called when the code references a class or interface that hasn’t been loaded yet . As time goes on , developers started to release their code-base to the programming community .Unfortunately , each developer adopted his/her own naming convention for defining Class-names . Its a common practice to combine different code-bases onto one single project . Due to the aforementioned “different naming convention” , an __autoload function had to implement different “ways” of importing Classes (usually it was done with “switch or loop statements” ) . The major drawback to the _autoload() function is that you can only define one autoloader within each PHP-project .Later on  (since  PHP > 5.1.2)  , the registration of multiple autoloaders was possible with  SPL’s spl_autoload_register function . A practical example is demonstrated below  :

<?php // A single autoload function
function __autoload($className) {
    $extensions = array(".php", ".class.php", ".inc");
    $paths = explode(PATH_SEPARATOR, get_include_path());
    $className = str_replace("_" , DIRECTORY_SEPARATOR, $className);
    foreach ($paths as $path) {
        $filename = $path . DIRECTORY_SEPARATOR . $className;
        foreach ($extensions as $ext) {
            if (is_readable($filename . $ext)) {
                require_once $filename . $ext;
                break;
           }
       }
    }
}

// Multiple autoloaders with SPL's register
function autoloadMail($className) {
    $filename = "mail/" . $className . ".php";
    if (is_readable($filename)) {
        require $filename;
    }
}

function autoloadLogger($className) {
    $filename = "Log/" . $className . ".php";
    if (is_readable($filename)) {
        require $filename;
    }
}

spl_autoload_register("autoloadMail");
spl_autoload_register("autoloadLogger");
 

PHP 5.3  introduced namespace support  , and a group of people from the PHP community decided to create  the PSR-0 standard which outlines various practices and constraints that must be followed for autoloader interoperability . Later on , the same group created the PSR-1 , PSR-2 and PSR-3 guidelines as an attempt to standardize coding-style and logger-interface practices .

No matter which autoload-method is used to reference a Class , PHP has to search  through all predefined paths (remember the autoload registers) until the required Class is found . This “scan-procedure” is repeated on each and every Class request , which obviously adds an extra overhead on the project’s  performance . Instead of doing runtime heavy directory scans or relaying on a properly configured include path  , the best way to implement an autoloader turned out to be a static Classmap . In simple words , a predefined list of Class-paths instruct the PHP interpreter to “go straight to the meat” instead of scanning the whole directory structure . Of course , the Classmap could be hard-coded (by hand) , that’s not a problem on small projects . On medium to large scale projects though , where tens if not hundreds of Classes are used to structure an application , that would be a nightmare .  A flexible tool to generate such a map alongside a matching function to implement the autoloader is provided by the phpab project  (PHP autoload builder) . This article will guide you through all required steps ( from installation to generating a Classmap ) , just follow along ….. (more…)

A Basic Introduction to PHP Streams April 4, 2013

Posted by Tournas Dimitrios in PHP.
2 comments

Streams is a feature of PHP that was introduced in PHP 4.3 to unify the methods for working on files , network-sockets , data compression , and other operations which share a common set of functionality . A stream is a resource object which exhibits “stream-able” behavior , in simple words , it can be read from or written to in a linear fashion , and may be able to fseek to an desired location within the stream . A few examples of streams could be :

  • A file on the file-system (server’s hard drive)
  • A HTTP connection to a web-server
  • A TCP , a UDP connection to a server
  • A FTP  connection , a SSH tunnel
  • A ZIP archive

By observing the above list , it is evident that even if these different stream-types share a common functionality (reading  , writing  ) , their implementation couldn’t be the same .  For instance , opening a compressed file (Zip-archive) needs a totally different “mechanism”compared to the “mechanism” used for opening a TCP-connection  . Another example , opening a file on the file-system (server’s hard drive) demands a much simpler “mechanism” than opening a stream socket , which implements “connection-oriented” semantics . Essentially , a “TCP network-stream” requires that the two communicating parties first establish a socket connection (in technical jargon — TCP is a connection oriented protocol) , after which any data passed through that connection will be guaranteed to arrive in the same order in which it was sent . Lastly , other network protocols (UDP)  prefer speed instead of secure-delivery , and utilize a connection-less oriented stream (which has no guarantee for secure delivery of the data) .  As in life , when developing web applications , we have to weigh the  needs and act upon compromises .

PHP has a set of functions that utilizes stream functionality , for instance : fopen() , file() ,  file_get_contents() , file_put_contents() . In fact , you have already been using file streams all the time , completely transparently . PHP also provides a set of predefined “wrapers” ,  which tells those aforementioned stream-functions how to handle specific protocols . There are many wrappers built into PHP by default , custom wrappers may be added either within a PHP script or from an extension using its API . A prime example of a wrapper that uses an extension’s API is the “ssh2://”  wrapper (it needs the SSH2 extension) . Because any variety of wrapper may be added to PHP , there is no limit on what can be done with them .

To access the list of registered wrappers , use the stream_get_wrappers()  function or open a phpinfo  file into your browser and locate the “Registered PHP Streams” section .  Notice : some shared hosts disable specific “wrappers” for security and / or performance .

By default , PHP uses the “file://” wrapper ,  however if you want to work with a different type of stream , you must specify it by pre-fixing your URI with “wrappername://” to indicate the stream wrapper/protocol that you wish to use .  As aforementioned , PHP has a long list of predefined “wrappers” .  Some examples of different wrappers follows :

Before we dig into practical examples , lets first mention an important feature of PHP’s stream-functions :

  •  stream context . The default functionality of each “wrapper” is adequate for basic tasks , we could further tweak each wrapper by specifying a few more options . It is obvious that each “wrapper” has its own set of options , for instance a HTTP protocol could be configured with an extra POST variable and or HEADER data . A FTP protocol , utilizes a totally different mechanism , it doesn’t need (nether supports) Post variables and HEADER data . FTP can be tweaked to overwrite an already existing files on the remote server or to Proxy a FTP request via http proxy server .The context is created with stream_context_create() . Options are set with stream_context_set_option() and parameters with stream_context_set_params() . Finally , here is  a list of supported context options and parameters  , notice : not all wrappers support / need configuration options .

Straight to practical examples : (more…)

Setting up SourceGear’s DiffMerge with Git on Windows 7 March 29, 2013

Posted by Tournas Dimitrios in PHP.
add a comment

Git is an open source version control system (VCS) , a command line tool for keeping a history on the state of your source code projects . It is fully distributed , which means that it can work almost entirely offline (compared to other VCS-tools like Subversion) .  As Git is primarily a command line tool , developers with a *nix  background will love it immediately . Those developers that doesn’t like the sentence “terminal”  have the option to use  GUI alternatives  (of course , with a subset of functionality) , which  act as frond-ends on top of Git’s command tool . A third option is to combine Git’s command tool with a few GUI applications  , for instance , replacing Git’s default text-editor (Vim) with Notepad++ ) .  This article will demonstrate how to configure  a GUI-based diff-editor to track differences between versions of an file . A Windows 7 is used to demonstrate the installation process , the same concepts apply on all Operating systems though .

DiffMerge is a cross-platform GUI-application to visually compare and merge files and folders .

Let’s stop for a minute to see how the git diff command can be used to show you the difference between the version of a file in the working directory , the stage and the most recent commit (or any commit made in the past) . The 3 main types of git diff commands you would likely use are :

  1. git diff   filename.php  :  Shows differences between the current state of a file in your working directory and the same file that was staged previously . 
  2. git diff  – -staged  filename.php :  Shows differences between a staged file  and its most recent ancestor (commit hystory) .
  3. git diff HEAD  – –  filename.php  : Shows the differences between a file in the working directory and its ancestor in the most recent commit  .

git-diff-on-the-terminal

The above screen-shot shows which lines were removed (in red color) and added (in green color) into the new version of the index.html file . Although it is handy to have a quick view of the current state of a file compared with its ancestor , a graphical representation is most likely a better approach .  Lets see how simple it is to configure Git to show the diffs into “DiffMerge” .

  • The first step is to install  “DiffMerge” on our machine  . 
  • Install msys|Git  : Its an environment for Windows offering a Unix-type shell and a Perl interpreter . Because many parts of Git are still not programmed in C , but instead shell and Perl scripts , Git for Windows needs such an environment .
  • Set path of DiffMerge into msysgit’s PATH : Open C:\Program Files\Git\etc\profile and append (on bottom of the file) –>
    export PATH=$PATH:”/c/Program Files/SourceGear/Common/DiffMerge”
  • Open msysgit’s console and run the following commands :  
    1. git config –global diff.tool diffmerge
    2. git config –global difftool.diffmerge.cmd ‘diffmerge “$LOCAL” “$REMOTE”‘
    3. git config –global merge.tool diffmerge
    4. git config –global mergetool.diffmerge.cmd ‘diffmerge –merge –result=”$MERGED” “$LOCAL” “$(if test -f “$BASE”; then echo “$BASE”; else echo “$LOCAL”; fi)” “$REMOTE”‘

Finally , open msyGit’s terminal create a project with a few commits and try to compare different versions of a file  :

git-diff-on-the-terminal-2

Accept (with a “y”) and msysGit  spawns the graphical DiffMerge application as seen on the following screenshot :

git-diff-on-the-terminal-3

How to Install Alternative PHP Cache (APC) on Windows (WAMP) March 13, 2013

Posted by Tournas Dimitrios in PHP.
5 comments

Alternative PHP Cache is a free open source extension for the PHP-engine (interpreter) . Its task is to store compiled results (bytecode) into shared memory (caching and optimizing PHP intermediate code) . If that sounds to cryptic , the following description is from the PHP-manual : “PHP is a script processing engine , which reads an input stream of data that contains text and/or PHP instructions and produces another stream of data , most commonly in the HTML format . This means that on a web server the PHP engine reads , parses , compiles and executes a PHP script each time that it is requested by a Web client . The reading , parsing and compilation operations puts additional load on the web server’s CPU and file system and thus affect the overall performance of a PHP web application . The PHP bytecode (opcode) cache is used to store the compiled script bytecode in shared memory so that it can be re-used by PHP engine for subsequent executions of the same script ”  .

For “heavy” applications consisting of a large source code base such as CMS Frameworks (WordPress , Drupal , Joomla , Zend , Symfony ) you can expect around a 3x increase in page generation speed as a result .There have been discussions about officially endorsement of  APC as a core feature in coming releases , it is scheduled for inclusion in the PHP core no later than PHP6 .

This article is just a quick “how-to install APC on WAMP ” for those developers that have chosen to develop their code on a Windows Os machine . A future article will go in more “depth” about the configurations that might affect (boost) the performance of this extension .  A bit of introspection has to be done before we can download the proper extension for our machine . First open a “phpinfo()”  file in you browser and note the following configurations (Ctrl + F on your browser) :

  • Loaded Configuration File”  : The location of PHP’s primary loaded configuration file
  • extension_dir”  : Where PHP expect to find all loaded extensions . On the Windows Platform , extensions have the “.dll” suffix .
  • Compiler”  : With what compiler Apache –the web-server —  was produced (on my machine its MSVC9 (Visual C++ 2008) ) . This information is crucial , as it defines which extension is compatible with the installed Apache .
  • Thread Safety”  : Most likely all Windows applications are “thread safe” , but to be sure , do a confirmation .

Pier’s website has a long list of pre-compiled extensions for the Windows Os . Each extension has the following signature “name–DateOfCreation–ReleaseNumber–ThreadMode–CompilerVersion–Platform.zip” . For instance , the following extension “php_apc-3.1.10-5.3-vc9-x86.zip” designates the following features .  It was compiled with a MSVC9 Compiler at 3 January 2010 , has release number 5.3 and is for a 32-bit platform (x86)  .  Notice : this extension has no “Thread_mode” designation in its name , so we make the assumption that this is a bundle of both “.dll’s” (ts and nts)  .  Other extensions may have the following name-convention php_xdebug-2.0.5-5.3-nts-Win32-VC9-x86.zip  , the “nts” designates a Non-Thread-Safe  extension .  Chose (and download) the extension that matches your machine’s  features . Unzip the downloaded extension into your PHP’s “extension_dir”  .  Caution : Some extensions have two folders in the downloaded zip-file (“nts” and “ts“) , chose the “.dll” that suits your machine (most likely “ts” — ie  : “Thread-Safe“– )  .  Now open PHP’s configuration file (php.ini) into your favorite text-editor and append the following directives into it :

extension=php_apc_319_php53_vc9.dll
[APC]
apc.enabled = 1
apc.shm_segments = 1
apc.shm_size = 64M
apc.max_file_size = 10M
apc.stat = 1

Final important step , restart your web-server and open “phpinfo()” into a browser to verify that the APC-extension is enabled .

apc_accelerator_on_wamp

On an old machine (a Windows box) which is used by me to do all kind of tests , no extension downloaded from Pier’s website was compatible with my installation . Finally , I found this website , it has a compiled version that was compatible for my Wamp . That’s it … Of course there is a lot more , for instance , 30 configuration directives can further tweak APC’s functionality . For a development machine , the default configuration options should do the job . On production machines , a bit of tweaking is necessary to adapt APC to its maximum functionality .

A few links for further reading :

Sending emails Using Zend_Mail and Google Smtp February 8, 2013

Posted by Tournas Dimitrios in PHP.
3 comments

mailboThe Zend Framework provides the Zend_Mail component to compose and send both text and MIME-compliant multipart e-mail messages . Due to ZF’s loosely coupled architecture , each component can be used as an supplementary part into other Frameworks or libraries . Mail can be sent with Zend_Mail’s default transport layer (Zend_Mail_Transport_Sendmail) or alternatively , using another transport layer  (Zend_Mail_Transport_Smtp) . This article will present a simple way to use the Smtp  layer for sending mails via our Google account . A custom Class encapsulates the basic functionality , this allows us to reuse the code in other projects (instead of copy/paste) . This Class depends on  ZF’s components , it is assumed that this Framework is already installed into your server . I always prefer to download the whole Framework , as its size is 35-MegaBytes (these days , it would be considered as negligible) .  You could of course only download  the needed modules (instead of the whole Framework) from this website .

Note: Google has smtp sending limits, you can only send up to 500 emails using a Google standard account. Read the Google answer on this limiting issue, for more info .

Straight to the code :

<?php
/**
 * Created by Tournas Dimitrios
 * Date: 2/7/13
 * Time: 10:38 PM
 */

class GoogleMailer
{
    protected $_parameters = array();

    public function __construct(array $mailComponents = array())
    {
     $this->_parameters = $mailComponents;
    }

    public function composeMail(array $mailComponents)
    {
    $mailer = $this->_getMailer() ;
 list($fromAddress , $fromName) = explode(",", $mailComponents['fromMail']);
    $mailer->setBodyText($mailComponents['plainTextMessage'])
           ->setFrom($fromAddress , $fromName)
           ->addTo($mailComponents['addTo'])
           ->setSubject($mailComponents['subject']);
    if (array_key_exists('HtmlMessage', $mailComponents) &&
        !empty($mailComponents['HtmlMessage']))
       {
    $mailer->setBodyHtml($mailComponents['HtmlMessage']) ;
       }
    if (array_key_exists('replyTo', $mailComponents) &&
        !empty($mailComponents['replyTo']))
       {
 list($replyAddress , $replyName) = explode(",", $mailComponents['replyTo']);
    $mailer->setReplyTo($replyAddress , $replyName );
       }
    return $mailer ;
    }

    private  function _getMailer()
    {
    $mailer = new Zend_Mail();
    $mailer->setDefaultTransport($this->_getSmtpTransport());
    return $mailer ;
    }

    private  function _getSmtpTransport()
    {
    return new Zend_Mail_Transport_Smtp('smtp.gmail.com', array(
            'auth'     => 'login',
            'username' => $this->_parameters['Google.username'],
            'password' => $this->_parameters['Google.password'],
            'ssl'      => 'ssl',
            'port'     => 465 ,
        ));
    }
}

A quick overview  :

  • The constructor demands an array , which contains our Google credentials (Username , password)
  • Two private functions ( _getMailer  and _getSmtpTransport ) are handling the initialization process of the Classes .
  • A public function (composeMail) , is responsible for triggering the initialization of the two required Classes  and composing the mail object with our custom information ( From , Subject , Message , MailTo  , ReplyTo) . The  information is passed into this function as an associative array .
  • Besides the required parts of the mail message , optional fields can also be defined (HtmlMessage and replyTo ) . Two “if-statements” will recognize their existence and will take care to set the mail object .  Gmail automatically replaces whatever “setFrom”  or “setReplyTo” fields you have specified with the account you are authenticating with (yourname@gmail.com) . To define another “setReplyTo”  mail-address , you must allow Gmail to send using that email address by following these steps  .

The implementation :

<?php
/**
 * Created by Tournas Dimitrios
 * Date: 2/7/13
 * Time: 11:16 PM
 */
include 'GoogleMailer.php' ;
require_once 'Zend/Loader/Autoloader.php';
$autoloader = Zend_Loader_Autoloader::getInstance();
$googleMail = new GoogleMailer(array(
    'Google.username' => 'YOUR-GOOGLE_USERNAME',
    'Google.password' => 'YOUR_GOOGLE_PASSWORD'));
$plainTextMessage = 'Lorem ipsum ....Vut integer et, nisi enim! Nisi lectus pid, nunc, eu aliquam aliquam sit montes cras. Aliquam mus non montes diam magnis placerat arcu augue, ' ;
$HtmlMessage = '<h3>Important message !!!</h3>' ;
$mailComponents = array(
    'plainTextMessage'=> $plainTextMessage ,
    'fromMail' => 'tournasdimitrios@gmail.com , Tournas Dimitrios ' ,
    'subject'  => 'Testing Zend_Mail with Google\'s SNMTP' ,
    'HtmlMessage' => $HtmlMessage . $plainTextMessage ,
    'replyTo'  => 'replytothisaddress@gmail.com , Tournas Dimitrios' ,
    'addTo' => 'sendtothisaddress@gmail.com');
    try
    {
     $mailer = $googleMail->composeMail($mailComponents)
                          ->send() ;
    echo 'Message send successfully' ;
    } catch(Exception $e) {
     echo $e->getMessage();
    }

A quick overview :

  •  First we have to include our custom GoogleMailer Class
  • Zend Framework’s components must also be included . Instead of separate “include” statements for each component , I have chosen to instantiate ZF’s  autoloader Class .
  • A “try-catch” block will handle possible errors .
  • Everything else is self-explanatory (if not , drop me a comment) .

Using Array-syntax to Access PHP-object Values January 24, 2013

Posted by Tournas Dimitrios in PHP.
add a comment

Since PHP 5 we can “cast” an object to an array and use array-like syntax to manipulate its content . This works fine on simple data-structures . However , often we write object-oriented code in which data isn’t necessarily represented as simple key/values (one dimension array) , but by more complex data structures  (ie hierarchical data — multi-dimensional arrays–) . Just casting an Object , which contains complex data structures , to an array won’t  lead to the desired results . The following code demonstrates my earlier definition :

<?php
/**
 * Created by Tournasdimitrios.
 * Date: 1/24/13
 * Time: 21:26 PM
 */
class TestCasting
{
    public $pubArray = array(
                'pubArray-one' ,
                'pubArray-two' ,
                'pubArray-three' ,
        array(
                'pubArray-nested-one',
                'pubArray-nested-two')) ;
    private $_privArray = array(
                'privArray-one' ,
                'privArray-two' ,
                'privArray-three') ;
    protected $_protArray = array(
                'protArray-one' ,
                'protArray-two' ,
                'protArray-three') ;
    public $pubVar = 'Content of Public variable' ;
    private $_privVar = 'Another value' ;
    protected $_protVar = "xyz" ;

    public function __construct()
    {
    echo 'Class', __CLASS__ . " is instantiated" ;
    }
    public function castToArray() {
    return get_object_vars($this) ;
    }

}

$casting = new TestCasting() ;
$results = (array) $casting ;
echo '<pre>' ;
print_r($results) ;

echo '<h3>Looping the results</h3>' ;
foreach($results as $k => $v) {
    if(is_array($v)){
        foreach($v as $kNested => $vNested){
          if(is_array($vNested))  continue ;
         echo '-----', $kNested , 'has value of  : ', $vNested , '<br>';
        } // End of inner loop
    } else {
        echo $k , 'has value of :' , $v , '<br>' ;

    } // End of if-statement
} // End of Outer loop
echo 'Public variable : ' , $results['pubVar'] , '<br>' ;

/*
 * Result on Browser
ClassTestCasting is instantiated
Array
(
    [pubArray] => Array
        (
            [0] => pubArray-one
            [1] => pubArray-two
            [2] => pubArray-three
            [3] => Array
                (
                    [0] => pubArray-nested-one
                    [1] => pubArray-nested-two
                )

        )

    [TestCasting_privArray] => Array
        (
            [0] => privArray-one
            [1] => privArray-two
            [2] => privArray-three
        )

    [*_protArray] => Array
        (
            [0] => protArray-one
            [1] => protArray-two
            [2] => protArray-three
        )

    [pubVar] => Content of Public variable
    [TestCasting_privVar] => Another value
    [*_protVar] => xyz
)
Looping the results

-----0has value of  : pubArray-one
-----1has value of  : pubArray-two
-----2has value of  : pubArray-three
-----0has value of  : privArray-one
-----1has value of  : privArray-two
-----2has value of  : privArray-three
-----0has value of  : protArray-one
-----1has value of  : protArray-two
-----2has value of  : protArray-three
pubVarhas value of :Content of Public variable
TestCasting_privVarhas value of :Another value
*_protVarhas value of :xyz
Public variable : Content of Public variable
 */

As seen on the results , casting an object (to an array) has some important gotchas :

  • The member-names of the object (properties , methods) are represented by the keys on the resulting array
  •  private variables have the class name prepended to the variable name and protected variables have a ‘*‘ prepended to the variable name .
  • data of private and protected “members” are not accessible .

One could implement variety of solutions , all depends on the desired result . For instance , do we want to reach only publicly accessible components of the instantiated Class (object) , or do we need accessibility to all components (public , private and protected) . The following code demonstrates both scenarios . (more…)

Exploring SPL : An Overview of the Iterator and IteratorAgreggate Interface January 23, 2013

Posted by Tournas Dimitrios in PHP.
add a comment

My previous article (introduction to Iterators) made a short introduction about Iterators and the basic concepts of their functionality . This article , and all articles that will follow , will present practical examples as an attempt to emphasize specific features of SPL’s Iterators . Usually  Iterators transform “simple objects” (arrays or instantiated Classes)  into “looping structures” with enhanced functionality , other times , Iterators replace standard loop tasks (foreach) with its own looping capabilities (exaggerating somehow … , creating loops on steroids ) . SPL’s “Iterator part” (my definition) has a hierarchical structure  of Interfaces and Classes . Knowing the general characteristics of each “component” on the aforementioned hierarchy is crucial , as it will determine which component is best suited for our application . The graph that follows presents the hierarchical “relationship” of  all components that constitute SPLs Iterator puzzle .

SPL--inherit_graph_

This article is an overview of the Iterator and IteratorAgreggate Interface . The best approach (IMO) to describe their functionality is by using practical examples , notice through , my attempt is to demystify the basic concepts by using simplified examples . The benefits that might be gained from these techniques may not be obvious at first view , but on production (with large data-sets) , they can boost the performance of an application .

By observing the above graph , one thing is immediately evident , all Classes (and four Interfaces — Countable , OuterIterator , RecursiveIterator , SeekableIterator –) inherit their features from Iterator and IteratorAgreggate Interface . The only exception to this ,  a stand-alone Class (SplInfo) , which is used as a basis for other Classes (SplObject and DirectoryIterator)  . Classes derived from SplInfo though , inherit from Iterator all its features . Traversable Interface is the root of SPL’s Iterator puzzle , its an internal-only Abstraction Interface , so trying to implement it in  “userland” Classes will simply result in an error . We can only implement Iterator or IteratorAggregate Interface into our code . (more…)