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

Thursday, October 25, 2007

A Rare Get Together Between Microsoft and An Open Source Family Member - PHP

I'm very much surprised to read a news about the co-operation between Microsoft and Open Source family member. And it got more attention since the Open Source involved is my PHP.

The main subject is "Microsoft is going to support the PHP in one or other way" interesting 'na! so continue read this...


The race between the Windows and Linux operating systems is multifaceted, and one aspect revolves around the PHP scripting language. But PHP is merely an item from an infrastructure of software, a solution stack designed to be the foundation of websites and servers. Essentially, Microsoft has recently upped the stakes in the Windows – Linux face-off by ensuring closer PHP integration with its own operating system in the much larger confrontation between LAMP and WISP. LAMP of course stands for Linux, Apache, MySQL and PHP. But now Microsoft comes with its own alternatives for an operating system, a web server, a database management system, offering Windows, IIS
and SQL. Still, one thing that Microsoft cannot do without is PHP, and this is why the Redmond company is embracing the scripting language.

"Why is WISP the new LAMP? Well, up to now, PHP developers, although they will be developing on top of Windows, the platform of choice for running their web servers etc, was Linux and Apache, with a MySQL back end. Why? Well, they were designed and written to work effectively together. PHP could be handled by IIS, using CGI, however it didn't give the level of performance that running PHP on a Linux/Apache platform gave, hence it became the platform of choice. With the announcement of FastCGI however, that's changing. This FastCGI extension is built into Server 2008, but you can download it for free, for IIS 5.1 and 6. Just a quick note - IIS has had 0 critical updates," explained Matt McSpirit, Microsoft Partner Technology Specialist.

You have of course already been able to read about the work Microsoft and Zend have poured into enhancing PHP performance on Windows, and about the availability of Go Live FastCGI Extension for IIS6.0 and IIS5.1. But now, McSpirit offers the true perspective of where Microsoft is going with the integration of FastCGI into Windows Server 2008. "So, you've now got a strong platform for development and actually running your web applications in Windows Server 2008 and IIS 7.0, along with a great database offering, all of which connect with PHP in a way that enables efficient, streamlined and powerful performance - something that was only available to PHP developers running on LAMP in the past", McSpirit added.

Source: Softpedia.com

Wednesday, February 07, 2007

Good Standards To Follow in PHP

In Software Development, most of the programmers have faced a very familiar situation of understanding other people codes for revamping or optimization. It's really challenging task to work in a maintenance project that demands cracking another programmers logic and thoughts. I equally love working in maintenance/optimization projects as like the new development projects. But as programmer I always strive hard to follow common standard while coding for a project. Coding style can vary by a bit for different project to avoid disinterest. Coding standards can be followed to maintain a consistent programming style throughout the core code base. If programmers follow guidelines it will be easier for others to understand and to maintain what has been developed if the project needs to optimized even after their stint.

I got sometime to work on finalizing standardizing the code styles that needs to be followed for future development... As these are very generic and can be useful for others I'm glad to share those.

Sections:
  • Naming Convention
  • Indentation/Tabs/Space Policy
  • Usage of Parens () with Key Words and Functions Policy
  • Control Structures
  • Function Calls
  • Function Definitions
  • Alignment of Declaration Blocks
  • No Magic Numbers
  • Comments
  • Others
  • Usage of ?:
  • Do Not Default If Test to Non-Zero
  • PHP Code Tags
  • Miscellaneous
Naming Convention

Class Names
  • Use upper case letters as word separators, lower case for the rest of a word
  • First character in a name is upper case
  • No underbars ('_')
  • When confronted with a situation where you could use an all upper case abbreviation instead use an initial upper case letter followed by all lower case letters. No matter what
Example
 class NameOneTwo

class Name

class GetHtmlStatistic

Method Names
  • Use the same rules as class
Example
 Connect()

GetData()

BuildSomeWidget()

Private class members
  • Class members that are intended to be used only from within the same class in which they are declared are preceded by a single underscore.
Example
 private $_mStatus

_Sort()

_InitTree()
Protected class members
  • Class members that are intended to be used only from within the same class in which they are declared or from subclasses that extend it are not preceded by a single underscore.

Example
 protected $mSomevar

protected function InitTree()

Class Attribute Names
  • Class member attribute names should be prefixed with the character 'm'
  • After the 'm' use the same rules as for class names
  • 'm' always precedes other name modifiers like 's' for static
Example
 $mVarAbc

$mErrorNumber

$msVolume

Method Argument Names
  • Methods argument names should be prefixed with the character 'a'
  • After the 'a' use the same rules as for class names
Example

function StartYourEngines($aSomeEngine, $aAnotherEngine, $aAgainOne)

Variable Names
  • Use all lower case letters
  • Use '_' as the word separator
Example
 $error

$an_example_for_var

Array Element
  • Array element names follow the same rules as a variable.
  • Use '_' as the word separator.
  • Don't use '-' as the word separator
  • Access an array's elements with single or double quotes
Example

$myarr['foo_bar'] = 'Hello';

Global Variables
  • Global variables should be prefixed with a 'g'
Example
 global $gLog

global $gTimeOut
Constants
  • Constants should always be all-uppercase, with underscores to separate words
  • Prefix constant names with the uppercased name of the class they are used in
Example
 GLOBAL_CONSTANT_FOR_EX
Static Variables
  • Static variables may be prefixed with 's'
Example
 static $msVolume

static $msVolume
Function Names
  • Use all lower case letters with '_' as the word delimiter
Example
 function some_function()
{
//code block
}
Indentation/Tabs/Space Policy
  • Indent using 4 spaces for each level
  • Do not use tabs, use spaces
Example
 function function()
{
if (something bad){
if (another thing bad){
while (more input){
}
}
}
}
Parens () with Key Words and Functions Policy
  • Do not put parens next to keywords. Put a space between
  • Do put parens next to function names
  • Do not use parens in return statements when it's not necessary
Example
 if (condition){
}

while (condition){
}

strcmp($s, $s1);

return 1;
Control Structures
  • These include if, for, while, switch, etc
  • Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls
  • Always use curly braces even in situations where they are technically optional. Having them increases readability and decreases the likelihood of logic errors being introduced when new lines are added.
Example
 if ((condition1) || (condition2)) {
action1;
} elseif ((condition3) && (condition4)) {
action2;
} else {
defaultaction;
}

switch (condition) {
case 1:{
action1;
break;
}
case 2:{
action2;
break;
}
default:{
defaultaction;
break;
}
}
Function Calls
  • Functions should be called with no spaces between the function name, the opening parenthesis, and the first parameter
  • Give single space between commas and each parameter, and no space between the last parameter, the closing parenthesis, and the semicolon
  • There should be one space on either side of an equals sign used to assign the return value of a function to a variable
Example
 foo($bar, $baz, $quux)

$short = foo($bar);

$long_variable = foo($baz);
Function Definitions
  • Arguments with default values go at the end of the argument list
  • Depends on where you are defining the function(Class or outside), use the appropriate naming convention
Example
 function connect($aDsn, $aPersistent = false)
{
return true;
}
Alignment of Declaration Blocks
  • Block of declarations should be aligned
Example
 var     $mDate

var& $mrDate

var& $mrName

var $mName


$mDate = 0;

$mrDate = NULL;

$mrName = 0;

$mName = NULL;

No Magic Numbers
  • A magic number is a bare-naked number used in source code. It's magic because no-one has a clue what it means including the author inside 3 months.
  • Instead of magic numbers use a real name that means something. You should use define() for example.
Bad Usage Example
 if (22 == $foo) {
start_thread();
} else if (19 == $foo) {
refund();
} else if (16 == $foo) {
infinite_loop();
}else {
blah_blah();
}
Correct Usage Example
 define("TIME_OUT", "22");
define("ROUND_UP", "19");
define("BREAK_DOWN", "16");

if (TIME_OUT == $foo) {
start_thread();
} else if (ROUND_UP == $foo) {
refund();
} else if (BREAK_DOWN == $foo) {
infinite_loop();
}else {
blah_blah();
}
Comments
  • Consider your comments a story describing the system.
  • Expect your comments to be extracted by a robot and formed into a man page.
  • Class comments are one part of the story, method signature comments are another part of the story, method arguments another part, and method implementation yet another part. All these parts should weave together and inform someone else at another point of time just exactly what you did and why.
Example
Comments at top of file:
 /*
* Short description for file
*
* Long description for file (if any)...
*
* @Module ModuleName
* @package PackageName
* @author Original Author
* @author Another Author
*/
Comments at top of class:
 /**
* Short description of class
*
* Long description of class (if any)...
* @Module ModuleName
* @package PackageName
*/
Comments at top of function:
 /**
* Short description of function
*
* Long description of function (if any)...
*
* @param $arg1 short description about first argument
* @param $arg1 short description about second argument
*
* @return short description what function will return
*
* @access specify the access type
* @static true/false
*/
function ShowResults($arg1, $arg2)
{
return 1;
}
Others

Usage of ?:
  • Put the condition in parens so as to set it off from other code
  • If possible, the actions for the test should be simple functions
  • Put the action for the then and else statement on a separate line unless it can be clearly put on one line
Example
 (condition) ? funct1() : func2();

(condition)
? long statement
: another long statement;
Do Not Default If Test to Non-Zero
  • Do not default the test for non-zero
Example
 if (FAIL != f())

is better than

if (f())
PHP Code Tags
  • Use standard approach to mark PHP codes like
Example
 <?php

?>
Miscellaneous
  • Do not do any real work in an object's constructor. Inside a constructor initialize variables only and/or do only actions that can't fail
  • There should be only one statement per line unless the statements are very closely related.
  • Always document a null body for a for or while statement so that it is clear that the null body is intentional and not missing code
Example
 while ($dest++ = $src++)
; // VOID
As usual comments are always welcome to discuss and make corrective measures.

Friday, February 02, 2007

Trapping Fatal Errors in PHP

Generally most of PHP programmers feels error handling in PHP is cumbersome or they think its just not very programmer friendly and impossible to handle fatal errors. In PHP 4.X.X versions or you can say PHP versions less that PHP 5, its possible to trap the errors with functions like set_error_handler() and trigger_error(). But the possible errors that can be handled by PHP 4 are just Warnings and Notices.

Many programmers have tried to find out ways to handle fatal errors that occur in a program, but never had patience or time to find out a viable solution. Fortunately I encountered a problem in that I must figure out some ways to handle fatal errors in PHP 4 in order to fix the issue. When I started working on this task, I looked all around globe(net) for some clues about how to handle fatal errors, but mostly all of them are either incomplete or not just straight forward that can be understandable instead thay used all sort of tech jerks to make the mud more murkier.

So here I am going to give a clear picture about how to handle fatal errors in PHP 4 with complete lab tested code that will actually work fine in all type of systems.

The main concept behind the logic I used to trap the fatal errors are output buffering. Output buffering is itself a important and big topic to discuss, and if we get into that then we will miss out from the track of our actual destination of trapping errors. So we can move on with first hand information about the output buffering.

The Output Control functions in PHP like ob_start() allows you to control when output is sent from the script. This can be used to control when a script output should be send back to browser.

Okay now I like to go straight into code and later on explain the basics.

FileName1: ErrorHandlerLib.php

<?php
//program to handle fatal errors in PHP 4

//set the error handler to catch unexpected errors
set_error_handler('LowCategoryErrors');
//start the buffering to catch the fatal error msgs
ob_start('FatalErrors');



/**
* function to handle different error types raised by PHP
*
* @return void
*/
function LowCategoryErrors($argErrNr, $argErrMsg, $argFileName, $argLineNr)
{
//initialize local variables
$szErrType = null;
$aErrorType = array(
E_ERROR => 'Error',
E_WARNING => 'Warning',
E_PARSE => 'Parser Error',
E_NOTICE => 'Notice',
E_CORE_ERROR => 'Core Error',
E_CORE_WARNING => 'Core Warning',
E_COMPILE_ERROR => 'Compile Error',
E_COMPILE_WARNING => 'Compile Warning',
E_USER_ERROR => 'User Error',
E_USER_WARNING => 'User Warning',
E_USER_NOTICE => 'User Notice',
);

//check we have value or not, else set default
if(array_key_exists($argErrNr, $aErrorType))
$szErrType = $aErrorType[$argErrNr];
else
$szErrType = "Unknown";

//form the error message string
$argErrMsg = "Caught PHP Error. $argErrMsg in $argFileName at $argLineNr.";

echo "<br>$szErrType: $argErrMsg\n";
}

/**
* function to handle Fatal error type raised by PHP. This works based on output buffering.
*
* @return string
*/
function FatalErrors($argBuffer = null)
{
//intialize local variables
$aMatches = array();
$argErrMsg = $retValue = $szErrType = null;
$tRes = true;

//parse the buffer to check whether there is any error or not
$tRes = preg_match_all("/<b>(.+?)\serror<\/b>:(.*?)<br/i", $argBuffer, $aMatches,PREG_SET_ORDER);

//diff the error and 0 return value
if($tRes===false)
{
$retValue = "<br>Fatal: Failed to evaluate regex pattern while validing the output buffer.\n";
}
elseif($tRes == 0)
{
//if we dont find any error, return the buffer content as it is
$retValue = $argBuffer;
}
else
{
//loop through the reg-ex patterns that is passed through arguments
for($iCount = 0; $iCount < count($aMatches); $iCount++)
{

//form the error message string
$argErrMsg = "Caught PHP {$aMatches[$iCount][1]} Error. Error Message: {$aMatches[$iCount]['2']}.";

echo "<br>Unrecoverable Error: $argErrMsg";

$retValue = "<br>$argErrMsg";
}
}

return $retValue;
}
?>


The function set_error_handler() here is used to register the error handler for warnings and notices. This will take care of lower category.

The second function ob_start() is the real king here. This registers the PHP buffer output handler and through this we are implementing the fatal error handling logic. This function FatalErrors() will called is there is any explicit call to end the buffer or else it will called whenever the PHP script is going to complete its final processing. Remember here, this function is also called whenever PHP going to end its execution. This makes us possible to trap fatal errors and do last minute processing.

FileName2: ErrorHandlerUsage.php

<?php

//program to demostrate the usage of fatal error handler

//include the error handler library
include "ErrorHandlerLib.php";

//error_reporting should be set to show all in order to catch fatal errors.
error_reporting(E_ALL);


echo "<br>Hello world";


/******************************************************************
Section1 : this makes notices and handled nicely by a handler
******************************************************************/

echo "<br>Im going to make some notices";

//the following statement will make the notice
$TestVar = $UndefinedVariable;

//End of Section1

/******************************************************************
Section2 : this makes warnings and handled nicely by a handler
******************************************************************/
echo "<br>Im going to make some warnings";

//the following statement will make the warning
implode('test');

//End of Section2

/*

//Uncomment this Section 3 only if you want to test the Fatal error handler, to test
//other type of error, just run the program.

//*****************************************************************
//Section3 : this makes warnings and handled nicely by a handler
//******************************************************************
echo "<br>Im going to make fatal error by calling undefined function";

//the following call to undefined functions makes fatal error
SomeJunk();

//End of Section3

*/
?>


The above code example is pretty much self explanatory and clearly spells out how trapping fatal errors are easy in PHP.

All this are just an example of single usage. You can customize outputting and last minute actions according to your needs and logics. You can implement this using object oriented programming logic in different way with other set of restrictions like freezing of object attributes by PHP.

If you like to clarify anything about this or just wanted to know one oe other about PHP you can trap me at kramchel-inet +at+ yahoo +dot+ co +dot+ in(replace the words +at+ and +dot+ with @ and . characters respectively). This is secondary mail ID I use to fight against spam. You can get my permanent ID after sending a first mail.

Happy Coding.