The Deployer

April 8, 2010

PHP on steroids – HipHop PHP

Filed under: PHP — Lucian Daniliuc @ 21:31

HipHop transforms your PHP source code into highly optimized C++ and then compiles it with g++ to build binary files. You keep coding in simpler PHP, then HipHop executes your source code in a semantically equivalent manner and sacrifices some rarely used features – such as eval() – in exchange for improved performance.

More info here:

March 30, 2010

Why You Can’t Work at Work

Filed under: PHP, Rapid development — Lucian Daniliuc @ 13:19

Lovely presentation, except the fact that it is advertising the products of 37signals, it does hold some truth:

If the embed doesn’t work, check it out here: http://bigthink.com/ideas/18522

October 3, 2009

Kohana & FastCGI routing problems

Filed under: PHP — Tags: — Lucian Daniliuc @ 20:11

If you’re developing on Kohana framework and your server is setup with Apache and FastCGI, you’ll run into some weird trouble regarding URL processing. This is happening because Kohana’s Router class is not looking at the REQUEST_URI key in the $_SERVER global, and gets the PHP_SELF instead that always returns the index.php file.

This has a workaround: either you alter the find_uri() method in the Router class, or you change the way the parameters are sent to the script via .htaccess’s mod_rewrite rules, as described in http://projects.kohanaphp.com/issues/1923.

May 18, 2009

Listing files in a directory with PHP

Filed under: PHP — Tags: , — Lucian Daniliuc @ 10:27

Listing the files in a directory in PHP is as simple as 1 line:

$aList = scandir( '/tmp' );
print_r( $aList );

This will retrieve all the files in the specified directory (including “.” and “..”):

Array
(
    [0] => .
    [1] => ..
    [2] => uioeng34890gn34.dat
)

April 14, 2009

Why should we use PHP constants inside classes

Filed under: Featured Articles, PHP — Tags: , , — Lucian Daniliuc @ 22:58
constant
A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren’t actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.

Practically, it’s as easy as:

define('DATABASE', 'thedatabase');

Constants are useful in a lot of cases:

  • Configuration directives

    Storing database connection information is plain easy and available everywhere.

    define( 'DATABASE', 'thedatabase' );
    define( 'USERNAME', 'theuser' );
    define( 'PASSWORD', 'thepass' );
    define( 'HOSTNAME', 'localhost' );

    These have global scope, cannot be tempered with and can be accessed from everywhere. How easy is that?

  • Anti-hack techniques

    You can make sure nobody accesses and uses your files remotely by checking a constant that you only define in one place, unaccessible from the web.

    if(!defined('ANTIHACK_FG3N4890FN4334G3GH')) die('You naughty');
  • Various flags

    Usually you need here and there to set some flags that activate or dezactivate some functionalities in your application, including debug flags.

    define('USE_CACHE', true);
    //.... some code....
    if(constant('USE_CACHE')) {
      //... cache data here
    }

    By using

    constant()

    , we don’t get a notice if the constant is not defined, and to disable the cache, you can take any approach you find suited: either set the defined constant to “false”, or comment it, the outcome is the same and you don’t get notices and warnings in your code, even if you completely remove the constant from your code.

So, you define the constants with define(), you check to see if certain constant is defined with the defined() function and you get the value of a constant that could or could not be defined using constant().

Using constants in classes

Along with the wonders of OOP in PHP 5 came the possibility to define constants inside classes. For example:

class AppSettings {
	const DATABASE = 'thedeployer';
	const HOSTNAME = 'localhost';
	const USERNAME = 'deployer';
	const PASSWORD = 'thepassword';
 
	public function __construct() {
		echo 'database = `' . self::DATABASE . '`';
		echo 'hostname = `' . self::HOSTNAME . '`';
		echo 'username = `' . self::USERNAME . '`';
		echo 'password = `' . self::PASSWORD . '`';
	} // END constructor
} // END class
 
echo 'database from outside = ' . AppSettings::DATABASE;

Basically, the constants ar a part of the class definition, you don’t have to actually execute code to define the constants and they are available immediately for use. And most important, you don’t have to instantiate a class to access it’s constants, and you always know where to look for the definition.

The advantages and differences that one should remember when using constants and the reasons to use constants in classes rather than just floating around in your code are:

  • Constants defined in classes do not show up in the global scope.

    There is a stack where PHP holds all the constants and it’s a rather large list. It’s nothing like the variables which are a total of 4 superglobals that exists when a script starts. To see the list of defined constants, just run:

    print_r(get_defined_constants());

    You’ll get a huge list of approximately 1760 defined constants when your script hasn’t got a line. This is a required compromise, because these constants include TRUE, FALSE, error codes, constants defined by enabled extensions and some other useful constants. This is why your constants shouldn’t go here. If you define your constants as part of some classes, they remain within the class definition and don’t end up in the constants pool. And don’t worry, even if they’re defined within a class, they are available everywhere, just like a normal constant.

  • Grouping the same type of data together.

    Usually, you can define a class that just deals with every piece of configuration data your application needs, just like de example above. This means that all your constants are in one place, and if you need to change a constant, you only need to find where the class is defined and change your info. You even have the class name, because you’ll be using the constants defined in some class this way:

    echo 'database from outside = ' . AppSettings::DATABASE;
    // this means that the "DATABASE" constant is defined in the "AppSettings" class.

    How easy is that?

  • Available without executing code.

    Since the constants are part of the class definition, they’re available before even the first line of actual code is executed.

  • Class autoloading power.If you have the autoload feature in use in your application, you’ll get another advantage. You’ll have the constants defined with a single call to the wanted class that contain the constants. The autoloader will locate an load you class.

These are just a few things that need to be said and noted when addressing constants. Be careful not to use constants where they’re not appropriate. For example in internationalization. Don’t define the i18n labels in constants. That’s a very greedy approach. Use gettext extension or some other dedicated solution for this. Using constants is just bad.

Happy coding and have a nice day!

March 29, 2009

APC – Alternative PHP Cache

Filed under: Featured Articles, PHP — Tags: , , — Lucian Daniliuc @ 23:53

APC is a simple and yet powerful PHP extension that does just that: caching. What for? Suppose you would have some piece of code that fetches some data from a table, and since you don’t use JOIN because you loose scalability, you’ll have to do some more SELECTs, and then format each row to be ready for display.

The other advantage is that it caches the compiled PHP source code in memory, serving it a lot faster.

Now if 100 users to this in one minute, (1) your server will fail to serve the pages because (2) it is doing a very complicated task that outputs the same result throughout the minute. This is where APC comes handy. You can save the retrieved data in the APC cache which holds it in memory and then just serve it to whoever asks for it.

The first thing to do is check if the APC extension is installed and running. For that you can look at phpinfo()’s result and check for APC. If it’s not, you should look in the php.ini file for the extension directive to be uncommented.

Using the APC cache requires three things:

  • a name (key) for the piece of information saved;
  • the actual data;
  • the TTL (time to live): how many seconds the information will be held in the cache.

The syntax to add data in the cache is as follows:

bool apc_add ( string $key, mixed $var [, int $ttl=0] )

So, $key is the name under which we’ll find the saved info, $var is the actual data and $ttl is an optional parameter to specify a time to live. If this function returns FALSE, something went wrong and the information isn’t cached. You’ll have to have some sort of fallback and never rely on the fact that you’re info is safe in the cache.

To retrieve the cached data, use apc_fetch():

mixed apc_fetch ( string $key [, bool &$success ] )

It’s that easy. Just ask for the saved key and you get it. If it’s not found or something goes wrong, this function returns FALSE and if the optional parameter was specified, sets that one too to FALSE.

That’s it. You have an up and running cache system.

Good practice: Regarding the usage of cache, there are two things you should keep in mind:

  1. you should build your code like there can be no caching done; that means 100% fallback. If the APC extension is disabled, your code should work.
  2. the specific APC caching functions should be wrapped up in some generic functions that call the actual functions. This thing will make you go light up a candle when – at some point – you’ll be switching to memcached or some other kind of caching, because you’ll only have to modify the contents of these wrapper functions, and not search & replace the entries in all your code.

Here’s an example on how to acomplish both these things:

function cacheWrite( $sKey, $mData, $iTtl ) {
  if( function_exists( 'apc_add ' ) ) { // we have APC
    return apc_add( $sKey, $mData, $iTtl );
  }
  return FALSE;
} // END func cacheWrite()
 
function cacheRead( $sKey ) {
  if( function_exists( 'apc_fetch' ) ) { // we have APC
    return apc_fetch( $sKey );
  }
  return FALSE;
} // END func cacheRead()
 
//---------- code that read/writes
 
$sKey = md5( $sQuery ); // same query will return same data, whithin minutes
if( ( $mData = cacheRead( $sKey ) ) === FALSE ) {
  // info not cached
  $mData = functionThatMakesUpTheData();
  cacheWrite( $sKey, $mData, 600 ); // cache the data for 10 minutes
}
// done, here we have our data, no matter if caching functions are available
// or not, if the info is in the cache or not

And to make it even more fun, APC comes with a nice online page that gives you all the information you need, including cache hits & misses (misses happen when the cache memory is full), a list of all the user-space cached data along with options to view or delete one or all the entries and much more.

October 11, 2008

How to setup Eclipse + XAMPP + Zend Optimizer + Debugging

Filed under: IDE, PHP — Lucian Daniliuc @ 15:02

[ This is currently a draft. will format and finish later ]

Eclipse all-in-one here:
Zend debugger here: http://downloads.zend.com/pdt/server-debugger/
How to allow Zend Debugger and Zend Optimizer to co-exist: http://blog.tigeryao.com/2008/how-to-allow-zend-optimizer-and-zend-debugger-coexist.html
XAMPP download:

Instructions on how to enable debugging for Eclipse:

Zend Debugger installation instructions
—————————————

1. Locate ZendDebugger.so or ZendDebugger.dll file that is compiled for the
correct version of PHP (4.3.x, 4.4.x, 5.0.x, 5.1.x, 5.2.x) in the
appropriate directory.

2. Add the following line to the php.ini file:
Linux and Mac OS X: zend_extension=/full/path/to/ZendDebugger.so
Windows: zend_extension_ts=/full/path/to/ZendDebugger.dll
Windows non-tread safe: zend_extension=/full/path/to/ZendDebugger.dll

(*) the windows non-thread safe is used only with Zend Core 2.0

3. Add the following lines to the php.ini file:
zend_debugger.allow_hosts=
zend_debugger.expose_remotely=always

4. Place dummy.php file in the document root directory.

5. Restart web server.

October 4, 2008

XML2Array

Filed under: PHP — Lucian Daniliuc @ 18:06

I’ve seen here the shortest xml2array implementation:

function xml2array($xml) {
$xmlary = array();

$reels = '/<(\w+)\s*([^\/>]*)\s*(?:\/>|>(.*)<\/\s*\\1\s*>)/s';
$reattrs = '/(\w+)=(?:"|\')([^"\']*)(:?"|\')/';

preg_match_all($reels, $xml, $elements);

foreach ($elements[1] as $ie => $xx) {
$xmlary[$ie]["name"] = $elements[1][$ie];

if ($attributes = trim($elements[2][$ie])) {
preg_match_all($reattrs, $attributes, $att);
foreach ($att[1] as $ia => $xx)
$xmlary[$ie]["attributes"][$att[1][$ia]] = $att[2][$ia];
}

$cdend = strpos($elements[3][$ie], "<");
if ($cdend > 0) {
$xmlary[$ie]["text"] = substr($elements[3][$ie], 0, $cdend - 1);
}

if (preg_match($reels, $elements[3][$ie]))
$xmlary[$ie]["elements"] = xml2array($elements[3][$ie]);
else if ($elements[3][$ie]) {
$xmlary[$ie]["text"] = $elements[3][$ie];
}
}

return $xmlary;
}

September 11, 2008

PHP file operations on large files fail

Filed under: PHP — Lucian Daniliuc @ 09:36

If you have a 2.7 GB file, file_exists(‘./filename’) works but is_file( ‘./filename’ ); fails gracefully. Not even Apache handles these kind of files very well so take care.

December 4, 2007

PHP Cron Daemon

Filed under: PHP — Lucian Daniliuc @ 19:08
Name: PHP Cron Daemon
Base name: phpcrondaemon
Description: Database driven PHP job scheduler like cron
Search tags: cron, schedule, daemon, scheduler
Version: 0.1
Required PHP version: 4.0
License: GNU General Public License (GPL)

Adresa:

http://www.phpclasses.org/browse/package/4140.html

Older Posts »

Powered by WordPress