21 years young

So its my 21st birthday today, time flies by fast. I remember being only 16 and learning PHP, and now its 5 years later and I am pretty proud of where I am. But anyways, I will be celebrating at Dave & Busters, playing some video games and having a beer. Just want to say hi to everyone out there reading this, and a premeditated thank you to everyone wishing me a happy birthday!

Stay tuned for a few new tutorials I have planned for the coming week.

XAMPP in Windows: Enabling InnoDB

I recently convinced my friend to start learning CakePHP and to install XAMPP for windows. Everything was going smoothly up until he needed to have the database engine InnoDB enabled. Here's a very quick tutorial on how to enable InnoDB on Windows XAMPP (might also work with other local servers).

I'm assuming you have installed the XAMPP directory into the root or C:/ drive. The first thing to do is to open the my.cnf located at C:/xampp/mysql/bin/my.cnf (Notice Your my.cnf file may have an icon that looks like a computer/phone and has a type called SpeedDial. Do not worry, this is the correct file. To open the file, first start Notepad and then locate the my.cnf file and open it). Locate the text below and add # to the beginning of it (# acts as a comment and disables the command).

#skip-innodb

The next and final step is to remove # from any line the begins with innodb_. Your file should now look something like the following. Once you have done this, save the file and InnoDB should be useable in your local server.

#skip-innodb
innodb_data_home_dir = "C:/xampp/mysql/"
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = "C:/xampp/mysql/"
innodb_log_arch_dir = "C:/xampp/mysql/"
innodb_buffer_pool_size = 16M
innodb_additional_mem_pool_size = 2M
innodb_log_file_size = 5M
innodb_log_buffer_size = 8M
innodb_flush_log_at_trx_commit = 1
innodb_lock_wait_timeout = 50

Commentia v1.2 Released!

I recently got a few emails from individuals about by Commentia script. They suggested that I add a settings system for the Behavior that loads on setup() (didn't know about this with the lack of documentation). Well to say the least I took their advice and redid the script so you don't have to manually edit the file, you just define the settings in the model. The documentation has been updated to reflect this change.

Download Commentia v1.2
View the complete change log

Databasic v1.10.2 Released

I have just released a new version of my MySQL database class, Databasic. This new version fixes a few issues with binds, MySQL functions and little bugs here and there. I have also added an "takes x seconds to execute the query" to every query in debug mode, no idea why I didn't add it before!

Update! There was a small bug in version 1.10.1 concerning the execute() method. I just patched it to 1.10.2, enjoy!

Download Databasic v1.10.2
View the complete change log

Custom PHP Functions: Datetime functions

All of these functions can be found within the Titon Utility library.

It is now time for my second post, in my series of "Basic/Common PHP functions that all programmers should know". The first series was about basic PHP strings and with this issue I am going to tackle 5 more functions for date and time. As always, I try to make my functions short but powerful, enjoy!

If you have any ideas for a series you want to see, or a type of function, be sure to send me an email using the contact page (in the footer), thanks!

Days Between

This function finds the difference in days between two dates. Each date must be a unix timestamp; if not my function will try to convert it to one. This could be modified to find the difference in weeks, seconds, etc.

/**
 * Finds difference in days between dates.
 * 
 * @param int $start
 * @param int $finish
 * @return int
 */
public function daysBetween($start, $finish) {
	if (!is_int($start))	$start = strtotime($start);
	if (!is_int($finish))	$finish = strtotime($finish);
	$diff = $finish - $start;
	$days = $diff / (24 * 3600);
	return round($days);
}
Get Age

This is a pretty simple function, in that it will find the persons age depending on the year given and the current year. The birth year could either be a string of '1988' (4 numeric characters) or the full date 1988-02-26.

/**
 * Gets the age of an individual.
 * 
 * @param int $timeStamp
 * @return int
 */
public function getAge($timeStamp) {
	$seconds = time() - strtotime($timeStamp);
	$year = 60 * 60 * 24 * 365;
	return floor($seconds / $year);
}
Get Date/Time in Timezones

Now this is something that could be done in many numerous ways, but mine simply takes the timezone difference (-8, 0, +6, etc) as the second argument, and then returns a unix timestamp. This function does not have any input checking (so make sure your arguments are correct before hand) and does not apply Daylight Savings Time.

/**
 * Gets a unix timestamp in certain timezones.
 * 
 * @param int $timeStamp
 * @param int $timeZone
 * @return int
 */
public function timeInZone($timeStamp, $timeZone = -8) {
	return strtotime(gmdate('Y-m-d h:i:sa', $timeStamp + (3600 * $timeZone)));
}
Date within a Timeframe

This function will take a date and check to see if it was within a certain date range and return a boolean value. My function will attempt to convert non unix timestamps to unix; be sure to pass the data correctly. Also you can leave the 3rd argument empty ($finish date) and the current time() will be used.

/**
 * Checks to see if a timestamp was within a timeframe.
 * 
 * @param int $check
 * @param int $start
 * @param int $finish
 * @return boolean
 */
public function withinTimeframe($check, $start, $finish = '') {
	if (!is_int($check))	$check = strtotime($check);
	if (!is_int($start))	$start = strtotime($start);
	if (empty($finish)) {
		$finish = time();
	} else {
		if (!is_int($finish)) $finish = strtotime($finish);
	}
	if ($check >= $start && $check <= $finish) {
		return true;
	}
	return false;
}
Breakdown a timestamp

Now this next function is quite different then the previous ones, but is pretty powerful. This function breaks down the timestamp to find how many days, weeks, months, etc there are until the current time (using time()). This type of function is good for doing text like: Last comment 5 days, 3 hours ago.

/**
 * Breaksdown a timestamp into an array of days, months, etc since the current time.
 * 
 * @param int $timeStamp
 * @return array
 */
public function timeBreakdown($timeStamp) {
	if (!is_int($timeStamp)) $timeStamp = strtotime($timeStamp);
	$currentTime = time();
	$periods = array(
		'years'         => 31556926,
		'months'        => 2629743,
		'weeks'         => 604800,
		'days'          => 86400,
		'hours'         => 3600,
		'minutes'       => 60,
		'seconds'       => 1
	);
	$durations = array(
		'years'         => 0,
		'months'        => 0,
		'weeks'         => 0,
		'days'          => 0,
		'hours'         => 0,
		'minutes'       => 0,
		'seconds'       => 0
	);
	if ($timeStamp) {
		$seconds = $currentTime - $timeStamp;
		if ($seconds <= 0){
			return $durations;
		}
		foreach ($periods as $period => $seconds_in_period) {
			if ($seconds >= $seconds_in_period) {
				$durations[$period] = floor($seconds / $seconds_in_period);
				$seconds -= $durations[$period] * $seconds_in_period;
			}
		}
	}
	return $durations;
}

And there you have it, 5 functions dealing with date and time. Stay tuned for the next issue! And again, if you have ideas for functions, send me an email!

My open-source scripts officially released!

So it has taken me nearly a year to get to this point. Over the past year I have been building some very advanced PHP classes and scripts that I wish to release as open-source. The types of scripts range from database handlers, template engines, form validation and cleaning, session management, CakePHP components and behaviors, so on and so forth. For the time being im releasing 3 scripts that I deemed "stable" and "complete". I hope you love them and get as much use out of them as I have. The following 3 scripts are now officially released to the public!

Databasic - A basic wrapper class for the MySQL database engine. Contains methods for connecting to a database, fetching and returning results, building insert and update queries, optimization and more.

Gears - A template engine that loads template files, binds variables to a single file or globally without the need for custom placeholders/variables, allows for parent-child hierarchy and parses the template structure.

Commentia - Commentia is a CakePHP Behavior that automatically runs after a comment is made. Each comment is tested upon a point system to determine and classify it. If a comment has more then 1 point it is automatically approved, if it has 0 points it continues pending, and if it is in the negative point range it is either marked as spam or deleted entirely.

Loading Models specific to certain actions

Recently I was working on a project, where a certain controller had over 15ish+ different models. The problem is that each action needed a different model, and I didn't want to load all those models at once. By using my common sense, loading that many models would put more of a strain on load time by having to initialize each model and bind them to the Controller. I needed a quick way to load a model(s) specific only to a certain action. At first I tried putting $this->user[] = array('Model'); at the top of each action, but that didn't work and it didn't initialize "before" the action like it is supposed to. So what I came up with is a little statement trick that you can place in your beforeFilter(), which will load models specific to certain actions. Enjoy!

/**
 * Executed before each action
 */
public function beforeFilter() {
	parent::beforeFilter();
	// Load action specific models
	switch ($this->params['action']) {
		case 'friends':		$models = array('Friend'); break;
		case 'messages':	$models = array('Message'); break;
		case 'blog':		$models = array('Entry', 'Comment'); break;
	}
	if (!empty($models)) {
		foreach ($models as $model) {
			$this->loadModel($model);
		}
	}
}

Also it would be best to disable models be default in controller. This way it doesn't load a certain model twice, or overwrite the defaults.

class TestController extends AppController {
	public $uses = null;
}