jump to navigation

Getting Started with Aspect Oriented Programming (AOP) in PHP July 29, 2014

Posted by Tournas Dimitrios in PHP.
Tags: ,
add a comment

Smiley Face

The benefits of Object Oriented Programming (OOP) is that it lets us encapsulate – abstract data and functionality away (which is the key for building large systems). We could achieve the same results with other paradigms, but it seems that OOP is especially helpful in this regard. Aspect Oriented Programming (AOP) is a follow-on development to OOP, developed with the intention of solving some of the practical limitations of OOP. The majority of applications a developer writes will contain common functionality that will be shared across the codebase (mailing, logging, caching, debugging, user-notification, security –ACL–, opening a database connection, etc….. ) . Such functionality is generally described as “cross-cutting concerns” because it’s not specifically relevant to any one piece of code where it might be embedded[used]. An example will better illustrate this subject (the following code is meant for illustrative purposes only; any design issues are beside the point) :

namespace MyNamespace\Controllers;

use MyNamespace\Services\Logger;
use MyNamespace\Services\Mailer;
use MyNamespace\Services\Security;
use MyNamespace\Services\AclException;
use MyNamespace\Models\User;

class UserController
{
     /*
     ..................
     Code truncated
     ..................
     */

    /**
    *
    * @param String $username Name of the new User
    */
    public function createNewUser($username)
    {
        $dateTime = date('l jS \of F Y h:i:s A');
        if (!$this->security->isGranted('Security::ROLE_ADMIN'))
        {
            throw new AclException('Only root can assign new users');
        }

        try {
            $user = new User($username);
            $this->entityManager->persist($user);
            $this->entityManager->flush();
        } catch (Exception $e) {
            $this->logger->error('User create error'. $e->getMessage());
            $this->mailer->send('User create error at : '. $dateTime);
        }

            $this->logger->info("User {$username} created at : " . $dateTime);
            $this->mailer->send("User {$username} created at : " . $dateTime);
    }
}

It is evident from the above code that the main role of the UserManager object is to manage users, but beyond this, UserManager has to borrow services from other objects in order to fulfill its operations. Most likely the same motif can be spotted across many places of our application (ie Logging, Mailing and Acl functionality will be used  by many objects).  The aforementioned motif is considered bad practice because it violates fundamental design principles and will lead to a system that isn’t easily maintainable-extendable over time. Let us identify a few of those violations :

  • SoC (Separation of Concerns) : Our UserManager object is tightly coupled to other objects. Distributing / Reusing the UserManager class into other projects has a dependency which must be taken into account.
  • SOLID : The above motif clearly violates the “O” of SOLID (ie the Open/Close principle). For instance, if for some reason one of those service-objects on which UserManager depends, change its functionality, this will affect UserManager (but also all objects that might use those service-objects). Having the task to update the relevant code throughout the entire system is not pleasant at all 🙂

Cross-cutting concerns  tends to increase the complexity of an application. AOP is a way of modularizing cross-cutting concerns much like object-oriented programming is a way of modularizing common concerns.

(more…)

Five Regular-Expression Concepts a PHP Developer Should Know July 14, 2014

Posted by Tournas Dimitrios in PHP.
Tags: ,
add a comment

Regular expressionsA Regular Expression, also called regex or regexp, is the term used to describe a codified method of searching into a string (or text) for a matched pattern. It was invented by an American mathematician, Stephen Cole Kleene (January 5, 1909 – January 25, 1994). Regex are used for advanced context sensitive searches and text modifications. Although regex are quite wide spread in the Unix world there is no such thing as ‘the standard regular expression language’. It is more like several different dialects. PHP supports two different types of regular expressions: POSIX-extended and Perl-Compatible Regular Expressions (PCRE). While the former is depreciated as of PHP version 5.3 and attempting to use any of its functions will result in the generation of a notice of level  E_DEPRECATED, it is highly encouraged to use the later (PCRE functions), which have native support for utf-8 character set encoding, are more powerful and faster than the POSIX ones.

Excerpt taken from a StackOverflow.com discussion : POSIX (Portable Operating System Interface for Unix) is simply a set of standards that define how to develop programs for UNIX (and its variants). Being POSIX-compliant for an OS means that it supports those standards (e.g., APIs), and thus can either natively run UNIX programs, or at least porting an application from UNIX to the target OS is easy/easier than if it did not support POSIX. Of course, the level of compliance is not necessarily 100% and can vary (e.g., not all features are supported or may be implemented differently).

For who is this article ? : Certainly not for a beginner in the world of “manipulating text programmatically“, neither for those that don’t like to experiment. The reader should have basic knowledge of regex syntax (he/she should be fluent with reading/writing regex patterns, so to speak). We will “talk” about : greediness , internal option settings , lookbehinds , lookaheads, non-capturing sequences and backreferences . Each of those concepts will be explained in brief and accompanied by a practical example.  This article aims to trigger your interest for writing more advanced regex patterns.

For those that need a refresh, at the end of this article (paragraph: “A quick overview of all PCRE functions” ) are practical examples for all PCRE functions. Also tables with metacharacters and pattern-modifiers are showing the most used “tools” (learn these tools by heart if you plan to master PCRE) .Of course, the official documentation is “the way to go”, for an in-depth review of the subject .

Whatever is done with regular expressions can also be achieved with native PHP functions (after all, PHP has close to one hundred functions for text manipulation), with one crucial difference though, regular expressions are doing it in a more efficient way. Not in the context of operating system performance but on the level of writing code. The following example will illustrate what I’m talking about :

/*  */

$contents = array(
    ' ALPHA ΒΑΝΚ ' => ' 0,6320 -0,0530 -7,74% 0,6260 0,6910 46.264.300 30.254.097 -',
    //    ......  truncated  .............  ///
    );

// Using PHP's string manipulation functions
foreach ($contents as $bank_name => $stock_values) {
    $stock_values =  str_replace('%', '', $stock_values);
    //first strip '-' and then strip whitespaces from beginning and end of string
    $cleaned_stock_values = trim(rtrim($stock_values, '-'));
    // the text is sliced and stored into an array
    $values = explode(' ', $cleaned_stock_values );
    $final_contents[$bank_name] =  $values;

}

// Using PCRE functions
foreach ($contents as $bank_name => $stock_values) {
$final_contents[$bank_name] = preg_split('/(-$)|[\s]|[%]/', $stock_values, null, PREG_SPLIT_NO_EMPTY);
}

var_dump($final_contents); 

/*
array (size=1)
  ' ALPHA ΒΑΝΚ ' =>
    array (size=7)
      0 => string '0,6320' (length=6)
      1 => string '-0,0530' (length=7)
      2 => string '-7,74' (length=5)
      3 => string '0,6260' (length=6)
      4 => string '0,6910' (length=6)
      5 => string '46.264.300' (length=10)
      6 => string '30.254.097' (length=10)
*/

/* */

Both approaches in the above code-snippet achieve the same goal, it’s evident that the regular expression solution is more compact (more readable I would say). For the curious spirits out there, the above example is an associative array whose values are strings of stock-market values which have to be sliced into separate entities. Firstly, each string has to be cleaned from unwanted characters (ie : %, – and white-spaces) and then the same string has to be transformed into an array. The outcome of this transformation can be used by Google Charts  and other custom code to extract statistical conclusions in order to create attractive and interactive charts. (more…)

An Overview of Exceptions in PHP July 5, 2014

Posted by Tournas Dimitrios in PHP.
add a comment

php exception graphAn Exception, as the name implies, is any condition experienced by a program that is unexpected or not handled within the normal scope of the code. Exception handling is prevalent among many popular languages ( Java , C++ , C# , Python to name a few) , it was added to PHP with the version 5 release.  When an Exception occurs, PHP’s default behavior is to :

  1. abruptly stop the flow of the program (code following the exception-event will not be executed),
  2. instantiate an object of type “Exception”  and passing valuable information into the object regarding the origin of the error (file , line , error-code, error-message).
  3. display a “Fatal error” message.

We can overwrite this default behavior though, by catching the Exception object, interfering with a custom — predefined — task (ie Logging the event , displaying a user friendly message) and continuing the program flow as nothing has happened. Actually there are two methodologies to catch exceptions (we’ll get into more details later on)

    A few keynotes :

  • Beside the fact that a user facing a “Fatal error” cannot perceive it as a pleasant experience, it might be a serious security risk (revealing sensitive information).
  •  A favorite expression used by developers is : “An Exception is thrown“.
  • Not only PHP’s interpreter can “throw” exceptions, also developers can “throw” exception-events programmatically by using PHP’s “throw” construct .
  • PHP has a long list of built-in exception classes .
  • An exception object can be catched with the “try/catch” construct . Sometimes it is helpful to catch an exception, look at some of its properties, and then re-throw it again. This is often useful to check an error code and decide whether it should be fatal.
    .

Before we dig into practical examples, let’s first present a few characteristics of PHP’s exception mechanism. (more…)

A Sample MVC App Build on Top of Symfony2 and Laravel4 Components (Part-2 Introspection of the Skeleton) June 22, 2014

Posted by Tournas Dimitrios in PHP, sample-MVC.
Tags:
add a comment

Word Cloud SymfonyWelcome back to the second part of the article series “A Sample MVC App Build on Top of Symfony2 and Laravel4 Components”. Every project start with a skeleton, it’s the application’s folder and file structure (a blueprint so to speak). Unfortunately, there are no standards in this regard. While some frameworks (Symfony , Zend-Framework, Laravel) utilizes a skeleton according their own philosophy other frameworks (in particular micro-frameworks) are giving the developer the freedom to structure a skeleton according their own needs. The key point here is that the structure of the skeleton must be planned in such a way that any developer that might get involved into the project will get familiar instantly.

A long time ago :), before PHP released its 5.3 version (at december 2010) we were forced to follow a particular folder structure. Certainly the following motif is familiar to you : class Zend_Application_Module_Autoloader extends Zend_Loader_Autoloader_Resource We had to follow a corresponding folder structure so that the autoloader could do its job, at some extent the same motif is also followed today but we are not forced to do so. PHP Namespaces, which were initially applied as a solution for bypassing naming conflicts between different libraries that could exist in the same project, had also impact how a skeleton could be structured. Due to Composer (a PHP dependency manager), we can now customize its autoloader in a much more flexible way.

The following picture shows the skeleton used by this app : skeleton_of_sampleMVC   A quick overview of each folder :

(more…)

Using ZF2′s ServiceManager Component to Lazy-load Dependencies on Standalone Codebases April 5, 2014

Posted by Tournas Dimitrios in PHP, Zend Framework 2.
Tags: , ,
1 comment so far

Zend Framework 2 logoThis article is intended to familiarize you with various features of  Zend Framework 2’s ServiceManager component (in short, SM). By demonstrating a couple of practical examples, concepts like : IOC , DI and SOLID principles are better digested. So, what is the ServiceManager used for ? In simple words, it’s a registry, or container that “holds” various objects needed by our application, allowing us to easily implement Inversion of Control. The main goal here is to be able to wire up and configure our application from the highest level possible. This results into an testable/maintainable and pluggable application (which I believe, is an objective of every [PHP] developer) .
By default, Zend Framework 2 utilizes Zend\ServiceManager\ServiceManager within its MVC layer (SM “plays” a central role). As such, knowing various features of this component (the SM) will allow us to better understand how  Zend Framework 2 is structured. Although the official documentation has an extensive introduction to SM’s concepts , it might be intimidating for a newcomer . This article will take an alternative approach to demonstrate SM’s basic features , it will detach the component from ZF2’s MVC layer and use it as a supplementary ingredient  into a standalone code-base. Besides all , ZF is composed from loosely coupled components .

Each object registered into SM provides a specific service to our application. A common web-application has services for : mailing , logging , authentication , session , database-connection , temporarily-storage … (the list goes on) . We distinguish these services by the kind of service they provide and how these services are instantiated (while some [objects|services] are autonomous blocks ,other objects have dependencies) . Zend Framework 2’s SM component has “labeled” its registered services (objects) as follows :

  • invokables
  • factories
  • aliases
  • initializers
  • abstract-factories

The official documentation has made a very good job in this regard (describing each service) , replicating its content has totally no meaning (neither could I do a better description) . In contrast , this article will use the first four services from the list ( invokables , factories , aliases and initializers) to build a simple logging application . The last service-type (abstract-factories) is omitted because it is difficult to demonstrate its functionality without breaking the barriers of this article’s simplicity .

Prerequisites : The reader should have a good grasp of OOP concepts . Also knowing to use Composer’s basic functionality is helpful , as it will be used to offload basic tasks like : downloading the required component and using its auto-load functionality .
Composer file used for this article :

{
	"repositories": [
		{
		    "type": "composer",
		    "url": "https://packages.zendframework.com/"
		}
	],
	"require": {
		"zendframework/zendframework": "2.2.*",
		"firephp/firephp-core": "*"
	}

}

Beside the fact that Zend Framework 2’s ServiceManager allows us to programmatically configure the instantiation of  objects (services) and their associated dependencies, these services are only instantiated the moment there is a need for their functionality. The process of instantiating a service/object (and its associated dependencies) at the moment these services are required, is named “Lazy loading” (I know , funny technical jargon). Three examples will clearly describe what I’m talking about :

  1. Why would we instantiate an object (service) if that object is not used by our application ? For instance  : why would we go through the whole process of querying a remote service , while we  have already cached the data from a previous request ?
  2. Why would we go through the whole process of establishing a database connection while our visitor hasn’t used the database in this current visit (for instance , he/she canceled the process of updating a Blog-article).
  3. Why would we go through the whole process of initiating a “Logging” object while this object will not be required on current request . For instance, our application was configured to “Log”  errors , but there hasn’t occurred an error during current session.

All frameworks nowadays ,  have plethora of features (services) . These services might be consumed, or might not be consumed (that  decision will be made by the visitor, most likely, momentarily ) . Lazy-loading has a notable impact into an application’s performance (CPU-cycles , memory consumption).

hooray picture

 

Hooray …. hooray , boring introduction is finished. Let’s begin the show with three practical examples .  (more…)

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 :