Scripts

Java-like import functie

Functie die je kunt gebruiken om alle bestanden, of 1, te laden uit een bepaalde dir. Als je 1 bestand wilt laden is het gebruik van deze functie totaal onnodig en een simpele include volstaat dan. Indien je een map hebt meerdere bestanden, en te lui bent om ze allemaal handmatig te laden is dit script dé perfecte uitkomt!

javalike-import-functie
[code]
<?php
/**
  * Java-like import mechanism to load all files in a directory.
  *
  * @param string $package
  * @return boolean
  */
  
function import( $package )
{
    // Check for dots in the package-string.
	if( !strpos( $package, '.' ) )
	{
		throw new Exception( 'I need some dots.' );
	}
	
	// Replace the dots with slashes.
	$packageLocation = str_replace( '.', DIRECTORY_SEPARATOR, $package ); // 'test/*'
	
	// Is this just one file, or a whole directory?
	if( !substr( $packageLocation, -1 ) == '*' )
	{
        // Load the file.
		require_once $packageLocation;
		
		// Return boolean true.
		return true;
	}
	
	// Real directory, without the last *.
	$realLocation = substr( $packageLocation, 0, -1 );
	
	// Is no directory?
	if( !is_dir( $realLocation ) )
	{
		throw new Exception( 'Package string contains invalid directory.' );
	}
	
	// Perform a search for all files in the directory.
	foreach( glob( $packageLocation . '.*' ) as $uniqueFile ) // add ".*" to the string so that only files will be found.
	{
		// Load the file.
		require_once $uniqueFile;
	}
	
	// Return boolean true.
	return true;	
}

import( 'test.*' );
[/code]

Reacties

0
Nog geen reacties.