July 15, 2010

DataGrid Control V2

I’ve been working on a series of “Control Objects” to include in my usual projects, and I thought I’d post one of the completed ones up here. Basically it mimcs the use of the DataGrid control in Visual Studio but in a way I find a lot easier and more in-tune with PHP. After creating the DataGrid, you define a “source”. The Source is essentially a multi-dimensional array that you could assign with a simple

while($r[] = mysql_fetch_array($resource)){}

you would then pass $r as the source to the DataGrid. You have the ability to set some options (like specifying specific style sheets, JS libraries for AJAX editing or defining and renaming visible columns) and then a single build(); command will output the table. Of course, you can also build(true); to return the table incase you’re using some sort of theme system.

$data = array(
  array('id'=>0,'f_name'=>'Angelo','l_name'=>'Rodrigues'), 
  array('id'=>1,'f_name'=>'Darth','l_name'=>'Vader'),
  array('id'=>2,'f_name'=>'Luke','l_name'=>'Skywalker'),
  array('id'=>3,'f_name'=>'Han','l_name'=>'Solo'),
);
 
$DataGrid = new DataGrid(); 
$DataGrid->configure(
  array(
    'primary_key' => 'id', 
    'sortable' => true, 
    'striped' => true,
    'even_row' => null, 
    'odd_row' => 'striped'
    )
);
 
// This not only defines display fields, but the order as well 
$fields = array( 
  'f_name' => 'First Name',
  'l_name' => 'Last Name',
);
$DataGrid->setDisplayFields($fields);
$headers = $DataGrid->Headers();
echo $headers['css']; 
echo $headers['js']['object'];
echo $headers['js']['function'];
 
 
$DataGrid->source($data); 
$DataGrid->build();

The code can be further simplified by using a new class called ControlObjectManager (or COM for short). COM can be used to instantiate multiple Controls at once and even assign shortcuts to commonly used Controls. For example, if you need DataGrids a lot, you can initiate them via a simple call like $COM->init(array('dg')) and as long as you set up that dg means DataGrid in the configuration for COM, you’re good to go.

I’ll post up some more on the COM when it’s done, but for now, here’s a link to the latest iteration of DataGrid v2.

View on Pastebin – Just note that this is the debug version of the script, so there are tons of comments and explanations.

The original DataGrid actually tied in to MySql directly and required the MySqlAdapter control to even function. This latest iteration removes all ties to any database instead focusing on a simple multi-dimensional array of data. As well it drops the code-base down quite a bit and condenses a lot of functionality. For example: originally you would have had to set the display columns and then order them, but by compressing them into a single function it not only makes MORE sense, but is easier to read.

October 28, 2009

A Default Config.php For All Your Projects

Wheneve rI start on a php project, I include the latest version of my config.php file from my Snippets section. This file contains my most commonly used functions and serve as the base from which I build whatever website/application I am working on. Instead of re-writing my config files differently for each application, I have a common setup that works for me. Here’s what it looks like.

  • Application Information
  • Variables
  • Functions

It’s very simple and I’ve included all the code below with numerous comments, as well as included the config.php file for download.

<?php
/*
 * @file		Config.php
 * @description	contains all essential functions and configuration options
 */
 
/*
 * Logging Directory
 */
define('LOG_DIR','logs/');
 
/*
 * Enable Logging?
 */ 
define('LOG',true);
 
/*
 * The database variables below configure the different databases. 
 * To set the database use the $use variable
 *
 */
$db['dev']['host'] = 'localhost'; 
$db['dev']['user'] = 'root'; 
$db['dev']['pass'] = 'root';
$db['dev']['name'] = 'test_db'; 
 
$use = $db['dev']; 
 
/*
 * Default class loader. To ensure single instances of each class, never initialize a class 
 * directly. Instead, use load_class(class_name) to initiate classes. 
 * 
 *  @param	string name of class to be loaded
 * 	@param	string path to class with trailing slash included
 *  @return	object reference to object
 */
function &load_class($class,$dir = './'){
	static $instance; 
 
	if(!isset($instance[$class])){
		if(file_exists($dir.$class.'.php')){
			include($dir.$class.'.php');
			$instance[$class] = new $class(); 
			return($instance[$class]);
		}
		else
			error($class.' does not exist in the Library'); 
	}
}
 
/*
 * Displays and optionally logs error messages
 * 
 * @param	string the message to be displayed
 * @param 	bool enables logging for particular message
 */
function error($message,$show = false){
 
	if(LOG){
		$file = LOG_DIR.''.date('d_m_y').'.log'; 
		$fp = fopen($file,'a'); 
		if(fwrite($fp,date('h:i:s a',time())."\t-\t".$message."\t".$_SERVER['PHP_SELF']."\r\n")){
			fclose($fp); 
		}
	}
	if($show){
		echo '<div class="error">'.$message.'</div>'; 
	}
}
?>

The only things that I feel need some clarification is the load_class() function and the error() function. The load_class() function will accept two different arguments. The first one is necessary and is the name of the class to be loaded. The second is the path to the class. It is not required if the class is in the same directory as the page being run. You would use it like this:

<?php 
$myclass = load_class('myclass','path/to/class/');
?>

The error() function also accepts two arguments. The first is the message that you want to be logged. The second is whether or not to force the system to display that particular message. Remember, you can still display a message a not log it. Logging is based on the LOG variable that is defined near the beginning of the file.

<?php
error('This error message will be logged only!'); 
error('This error message will be logged AND displayed!',true);
?>

Download The Config.php File from here!

October 27, 2009

mod_url without mod_url?

I know the title seems to make no sense but bear with me a minute. mod_url is an extension for the apache server that allows you to specify automatic routes for urls. So someone going to http://wheremy.feethavebeen.com/xangelo would see their profile page instead of going to http://wheremy.feethavebeen.com/profile?=xangelo It’s just a pretty way of formatting URLs. As an experiment, I decided to construct a handy little function that will allow you to parse links like http://wheremy.feethavebeen.com/index.php/profile/xangelo/view to create a more readable url structure.

<?php
function parse(){
		$self = $_SERVER['PHP_SELF']; 
		$e = explode('index.php',$self);
                $t = array();
		$t['base'] = $e[0]; 
		$x = explode('/',$e[1]); 
 
		foreach($x as $key=>$val){
			if($val == '')
				unset($x[$key]); 
		}
		$t = array_values($x); 
                return $t;
	}
?>

To create a link to the same page the array key ‘base’ can be used followed by a / and then the options you want. To create a link to my profile you could do this:

<?php
$url = parse(); 
echo '<a href="'.$url['base'].'/profile/xangelo/view">My Profile</a>';
?>