The Deployer

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!

CodeIgniter 1.6 + Rapyd library download

Filed under: Downloads — Tags: , , , — Lucian Daniliuc @ 08:00

When I need to develop a fast-growing, flexible and complex management application that needs to be done in a very short time, I use a CodeIgniter – Rapyd “bundle” that I’ve built to work, which can be turned into a really complex application.

Actually, I’ve built a complex management application, and then stripped down all it’s business logic so that only the framework to build another remained.

As you may know, Rapyd is no longer being maintained for CI, but has moved to Kohana framework. So, if you need a solid framework to build you application and you don’t want to loose any time with the building blocks for basic functionality like displaying a data table, filtering, sorting, adding, modifying and deleting entries, just use this.

Download CodeIgniter 1.6 + Rapyd

Here are some screenshots of what can be done in just a few hours…

rapyd-screenshot1

rapyd-screenshot2

rapyd-screenshot3

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.

Powered by WordPress