Creating a custom XML logger for SugarCRM 7

I recently ran across a question on StackOverflow in which the original poster asked about creating a custom XML logger for SugarCRM. He was wondering where to put his custom class and some of the particulars surrounding this so I thought I’d pitch in and help out.

I created my own custom XML logger class – SugarXMLLogger – and saved it at custom/include/SugarLogger/SugarXMLLogger.php. I then applied it to the Ping API for testing both as a replacement for fatal level logging and as a replacement for the default logger. Since the functionality of the logger is intended to be simple, I didn’t feel the need to extend SugarLogger. However, I did feel it at least appropriate to implement LoggerTemplate so that the integrity of the logger among the stack of loggers was kept in tact. If you want the fullness of SugarLogger in your custom loggers then you should extend SugarLogger. However, for a simple XML logger that wasn’t absolutely necessary.

As far as the log is concerned, I kept all the same information as is normally in sugarcrm.log with the only change being how it is stored. Since XML is structured it made sense to structure the logged information accordingly. So, without further ado, here is the code for the SugarXMLLogger…

The SugarXMLLogger Class

<?php
/** 
 * Save to custom/include/SugarLogger/SugarXMLLogger.php
 * 
 * Usage: 
 * To make one particular log level write to the XML log do this:
 * ```php
 * <?php
 * LoggerManager::setLogger('fatal', 'SugarXMLLogger');
 * $GLOBALS['log']->fatal('Testing out the XML logger');
 * ```
 * 
 * To make all levels log to the XML log, do this
 * ```php
 * <?php
 * LoggerManager::setLogger('default', 'SugarXMLLogger');
 * $GLOBALS['log']->warn('Testing out the XML logger');
 * ```
 */
 
/**
 * Get the interface that this logger should implement
 */
require_once 'include/SugarLogger/LoggerTemplate.php';
 
/**
 * SugarXMLLogger - A very simple logger that will save log entries into an XML
 * log file
 */
class SugarXMLLogger implements LoggerTemplate
{
    /**
     * The name of the log file
     * 
     * @var string
     */
    protected $logfile = 'sugarcrm.log.xml';
 
    /**
     * The format for the timestamp entry of the log
     * 
     * @var string
     */
    protected $dateFormat = '%c';
 
    /**
     * The current SimpleXMLElement logger resource
     * 
     * @var SimpleXMLElement
     */
    protected $currentData;
 
    /**
     * Logs an entry to the XML log
     * 
     * @param string $level The log level being logged
     * @param array $message The message to log
     * @return boolean True if the log was saved
     */
    public function log($level, $message)
    {
        // Get the current log XML
        $this->setCurrentLog();
 
        // Append to it
        $this->appendToLog($level, $message);
 
        // Save it
        return $this->saveLog();
    }
 
    /**
     * Saves the log file
     * 
     * @return boolean True if the save was successful
     */
    protected function saveLog()
    {
        $write = $this->currentData->asXML();
        return sugar_file_put_contents_atomic($this->logfile, $write);
    }
 
    /**
     * Sets the SimpleXMLElement log object
     * 
     * If there is an existing log, it will consume it. Otherwise it will create
     * a SimpleXMLElement object from a default construct.
     */
    protected function setCurrentLog()
    {
        if (file_exists($this->logfile)) {
            $this->currentData = simplexml_load_file($this->logfile);
        } else {
            sugar_touch($this->logfile);
            $this->currentData = simplexml_load_string("<?xml version='1.0' standalone='yes'?><entries></entries>");
        }
    }
 
    /**
     * Adds an entry of level $level to the log, with message $message
     * 
     * @param string $level The log level being logged
     * @param array $message The message to log
     */
    protected function appendToLog($level, $message)
    {
        // Set some basics needed for every entry, starting with the current
        // user id
        $userID = $this->getUserID();
 
        // Get the process id
        $pid = getmypid();
 
        // Get the message to log
        $message = $this->getMessage($message);
 
        // Set the timestamp
        $timestamp = strftime($this->dateFormat);
 
        // Add it to the data now
        $newEntry = $this->currentData->addChild('entry');
        $newEntry->addChild('timestamp', $timestamp);
        $newEntry->addChild('pid', $pid);
        $newEntry->addChild('userid', $userID);
        $newEntry->addChild('level', $level);
        $newEntry->addChild('message', $message);
    }
 
    /**
     * Gets the user id for the current user, or '-none-' if the current user ID
     * is not attainable
     * 
     * @return string The ID of the current user
     */
    protected function getUserID()
    {
        if (!empty($GLOBALS['current_user']->id)) {
            return $GLOBALS['current_user']->id;
        } 
 
        return '-none-';
    }
 
    /**
     * Gets the message in a loggable format
     * 
     * @param mixed $message The message to log, as a string or an array
     * @return string The message to log, as a string
     */
    protected function getMessage($message)
    {
        if (is_array($message) && count($message) == 1) {
            $message = array_shift($message);
        }
 
        // change to a human-readable array output if it's any other array
        if (is_array($message)) {
            $message = print_r($message,true);
        }
 
        return $message;
    }
}

The structure of the log

<?xml version="1.0" standalone="yes"?>
<entries>
    <entry>
        <timestamp>Wed Oct  8 11:56:04 2014</timestamp>
        <pid>89160</pid>
        <userid>1</userid>
        <level>fatal</level>
        <message>Testing out the XML logger</message>
    </entry>
</entries>

How to log only fatal logs to the XML log

<?php
LoggerManager::setLogger('fatal', 'SugarXMLLogger');
$GLOBALS['log']->fatal('Testing out the XML logger');
?>

How to log all logs to the XML log

<?php
LoggerManager::setLogger('default', 'SugarXMLLogger');
$GLOBALS['log']->warn('Testing out the XML logger');

Negative number PHP array indexes, var_export and WTF

Those folks that know me in the programming, web development or technology context know that I am a PHP fanboi to the nth degree. I eat, sleep, breath and live PHP. It is my very favorite programming language and it is the language that I learned how to program in. I stand behind it and have defended it – often – against the attacks of many a strict-type-language zealot from the world of .NET or Java or even Ruby. Seriously, I love PHP with all of $my <3;

However, these same people that know my insane and indescribable love for "my" language also know that I am usually very fast to point out some of it's major stupidities and illogical implementations. Which comes first, the $haystack or the $needle? Is it a str_* function or a str* function? Are the array function args passed by reference or am I expected to handle a return? There are so many of these little issues with PHP that sometimes I, myself, have no choice but to ask... WTF?

Today is one of those days. I am working on a bug for work in which the number -99 is somehow magically being transformed into -9223372036854775808 and is causing significant problems for our application. In doing some trouble shooting, I discovered that, as part of our process of caching some information, we use the var_export() function to write out an array to a file and somewhere between the passing of the data to var_export and the file that the exported data is written to, the -99, when used as an array index, suddenly became 18446744073709551517. This did not happen when -99 was the value of a scalar variable nor when it was a value assigned to an object property.

Looking a little closer I found that this particular server was running PHP 5.2.17 on CentOS, so I decided to dig even deeper and try this on other versions of PHP. On my 5.3.6 version of PHP on my Mac I could not reproduce the issue. But I was able to reproduce it on 5.2.17 on my Mac. My colleague was likewise able to reproduce it on 5.2.10 on his Ubuntu installation. And I was able to reproduce it on several PHP versions using 3v4l.org.

I'm not exactly sure what is going on under the hood, but my suspicion is that because PHP does not support unsigned integers it needs to convert the signed int -99 to an unsigned value in order to store it in the symbol table. I suspect when var_export is called, this unsigned value is being returned rather than the signed value. At the very least, this is an issue that will more than likely never be corrected since PHP 5.2 is now out of date and this problem, as far as I can tell, does not expose itself in 5.3 save for 5.3.3.

Regardless, if you want to see this for yourself and you have a 5.2 build laying around somewhere (or a 5.3.3 build), give this little snippet a shot and see what you get:

<?php
for ($i = 10; $i > -101; $i--) {
    echo "$i...\n";
    $q = array($i => 'this');
    var_export($q);
    echo "\n";
}

Or, if you just want to see it without a bunch of output, try this:

<?php
$a[-99] = 'bilk';
var_export($a);

As an added bonus, take the broken translated value and use that as an array index, then var_export that. You might pleasantly surprised by what you see I'd bet.

All of this is to say, if you are still using PHP 5.2 - and let's be honest, who is really using PHP 5.2 any more aside from those that have it on a test server - and you are using var_export on an array with signed int indexes, you are probably not going to get what you expect out of it. You have been warned.

Also? WTF PHP?

Pair programming with a child

While driving home today my daughter Alaynah asked me a little bit about what I do. After explaining to her that I am a software engineer and that I write programs, and telling her that my programs run on the internet, she asked me how Google makes that little box “that you type in to look stuff up”. I told her when we got home I’d show her since it was pretty easy to do.

When we got home we got to work. And a coupe of minutes later we had a very simple web “program” that took some text in a text box and wrote it out to the screen a certain number of times, each time making the text bigger. Not a lot of action going on there, but still something she could see that involved a text box and some programming logic. And as uneventful as this little application might have been, what it led to was amazing to say the least.

As we started to look at the words “Awesome Alaynah” explode onto my monitor in ever growing size, Alaynah began to look at the lines and count them to make sure there were as many lines of repeating text as she had selected. So we decided that it would be easier if there were numbers next to each line so we could see just how many lines were on the screen. Then, after she saw that, she asked me “is there a way to make it so if you click on a line, that all of the lines after it just disappear, including the line that you clicked on?”. I told her that I was sure there was, but that we needed a different kind of programming for that (since our original program was all PHP and click events, while potentially served by the server, are better handled on the client). So I went and got us jQuery, included it and wrote the code that made the lines disappear from the line you clicked on.

As she sat in amazement watching the lines disappear when clicked you could see that there was something troubling her. It was almost as if, when the lines were disappearing, that they were gone forever and ever. So I wrote a little bit of code that would bring the lines back if you wanted them back. She loved that. Except for the text to bring the lines back was “Bring them all back”, which works in all cases except if you disappeared the last line, because there aren’t any “all” lines, only “the” line. So she told me that we needed to change it so that if you removed the last line that to bring it back, the program should say “Bring it back” instead. So we fixed that, and after only a few minutes of conceptualizing, programming, testing, using and refactoring, Alaynah and I had put together a little program that we were both pretty proud of. You can view the source of this little program here.

Now aside from the obvious goodness that is my eight year old daughter (who happens to be turning nine tomorrow) taking an interest in the work I do, I have to say that having time to spend with my daughter – just her and me time – was a blessing. I don’t get a whole lot of one on one time with any of my kids. And even though this was only a few minutes, it was a cool few minutes that let me show my daughter what I do, let her do it with me and let us both enjoy some quality time together. I’m certain I would have loved it just as much if we had been talking about dolls, mud, cartoons or our favorite foods, but the fact is, we were talking about programming, my work, her ideas and our time together. There is a lesson in this for any parent. If your child shows any kind of interest in what you do, take the time to show him/her what it is you do. Don’t explain it with words and leave it at that. If you can take the time to allow your kids to connect with you while learning you, take that time. No excuses, no fussing, just do it.

She and I had an awesome time with this, even if it was only a few minutes. It was a great time and I am glad I didn’t pass it up because I was tired, wasn’t interested or was just unavailable.

View the source of our little program
Our original code was a little more rough around the edges than this one. After we got it working the way we wanted it I went through and cleaned things up a bit, added some comments, pulled out duplicated javascript code segments, etc. So the final product is a cleaned up rendition of our original stuff, which we hacked together very quickly in an effort to make it just work.

<?php
// Iterations max limit
$max = 30;
 
// Iterations min limit
$min = 5;
 
// User supplied iterations count
$limit = null;
 
// Handle posted values
if (!empty($_POST['limit'])) {
	$limit = intval($_POST['limit']);
	if ($limit > $max) {
		$limit = $max;
	}
 
	if ($limit < $min) {
		$limit = $min;
	}
}
 
$words = empty($_POST['words']) ? null : $_POST['words'];
?>
<html>
<head>
	<title>Alaynah's program</title>
	<style type="text/css">
		#putitback {
			color: #008;
			cursor: pointer;
			text-decoration: underline;
			margin-top: 20px;
		}
 
		.index {
			display: inline-block; 
			width: 50px;
		}
	</style>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
	<script type="text/javascript">
		$(function() {
			// Set the row prefix
			var rowprefix = 'row-';
 
			// The id of the clicked row to make hide from
			var rowid;
 
			// Row toggler, makes rows appear and disappear
			function toggleRows() {
				for (var i = rowid; i <= <?php echo $limit; ?>; i++) {
					$("#" + rowprefix + i).toggle();
				}
			}
 
			$('.row').click(function() {
				// Get the row id that was just clicked
				rowid = $(this).attr('id').replace(rowprefix, '');
 
				// Handle visibility toggling
				toggleRows();
 
				// Set our message for restoring rows
				var message = 'Put them all back.'
				if (rowid == <?php echo $limit; ?>) {
					// Alaynah was smart enough to see that if you only plucked
					// the last row the message should be singular
					message = 'Put it back';
				}
 
				$('#putitback').text(message);
			});
 
			// Handle restoring "removed" rows
			$('#putitback').click(function() {
				// Handle visibility toggling
				toggleRows();
 
				// Clear out the restore link since everything is back to normal
				$(this).text('');
			});
		});
	</script>
</head>
 
<body>
<h1>Alaynah&apos;s program</h1>
<form action="" method="post">
	<p>What do you want to write? <input type="text" name="words" value="<?php echo $words ?>" /></p>
	<p>How many times do you want to see it? 
		<select name="limit">
			<?php for ($i = $min; $i <= $max; $i++): ?>
			<option value="<?php echo $i ?>"<?php if ($i == $limit) echo ' selected="selected"'; ?>><?php echo $i; ?></option>
			<?php endfor; ?>
		</select>
	</p>
	<p><input type="submit" value="Hit it!" /></p>
</form>
<?php if ($limit && $words): ?>
<hr />
<?php /* Loop $limit times and make the displayed text grow each iteration */ ?>
<?php for ($i = 0; $i < $limit; $i++): $c = $i + 1; ?>
	<div class="row" id="row-<?php echo $c ?>" style="font-size: <?php echo (14 + $i); ?>px;">
		<span class="index"><?php echo $c; ?></span>
		<span><?php echo $words; ?></span>
	</div>
<?php endfor; ?>
<div id="putitback"></div>
<?php endif; ?>
</body>
</html>

Storing singleton objects in PHP sessions

A friend of mine, who is working on a sick little diet and exercise tracking application, asked me today if PHP allowed singleton objects to be stored in a session. My first reaction was absolutely they can be so long as you follow the normal rules of unserializing objects in PHP… namely, making sure the class is in scope before attempting to create an object from it OR having an autoloader that does that for you. But as I thought about it more I began to think that maybe this might not work as expected since singletons generally have no public access to their constructors. However, when an object is unserialized, it is instantiated, for lack of a better term, and populated with the data that was exposed from the serialization process.

Note: for those of you that are unfamiliar with the way PHP handles session data or are just wondering why I am using serialization so much in my examples, the basics are you start a session and PHP assigns a random MD5 hash to it as an id. You write data to the session via the $_SESSION superglobal array and when the script terminates or you call session_write_close(), PHP serializes the $_SESSION array and writes that serialized string to the file system for retrieval on subsequent requests so long as the session time limit has not expired. I really did not want to run this entire session process and inspect what was being written to my file system so I decided to mock that interaction myself by creating an arbitrary array, serializing it, grabbing the serialized string and unserializing it.

As I began to dig into this I started playing with PHP’s magic __sleep() and __wakeup() methods. Those seemed to do what I wanted them to do except in the case of protected and private properties of my class. As soon as I added those in my serialization took a crap all over itself, even when I cloned the singleton object and got the public properties exposed through get_object_vars(). So, thanks to the PHP manual – the most awesome tool in any PHP developer’s arsenal – I discovered the PHP Serializable interface.

This interface defines two methods: serialize() and unserialize(). These methods override the default behavior of __destruct() and __construct() so if you are using these you should keep that in mind and either put your __destruct() and __construct() code into these methods or allow for calls to __destruct() and __construct() from within these methods. Your homework is to decide which is the better implementation. 🙂

Now, back to the lesson at hand… the following object – let’s say it is saved to a file named dummy.php – is a super simple implementation of a basic singleton pattern. It includes both a serialize() and unserialize() method to allow it to be serialized for storage.

<?php
class DummySingleton implements Serializable {
    /**
     * Test properties of various visibility
     * @var string
     */
    public $dProp;
    public $dPropX = 'Nothing to see here folks';
    private $_prop = 'y u try see dis?';
 
    /**
     * Instance holder for this singleton
     * 
     * @var DummySingleton
     */
    private static $_instance = null;
 
    /**
     * Private singleton constructor, simply sets a property
     */
    final private function __construct() {
        $this->dProp = 'I was finally built';
    }
 
    /**
     * Singleton instance getter
     * 
     * @return DummySingleton
     */
    public static function getInstance() {
        if (self::$_instance === null) {
            self::$_instance = new DummySingleton();
        }
 
        return self::$_instance;
    }
 
    /**
     * Implementation of the Serializable interface, called automatically just 
     * before this object is serialized. This will override any calls to a
     * __destruct method, so if you have a destructor you should call it from
     * here.
     * 
     * @return string
     */
    public function serialize() {
        return serialize(get_object_vars($this));
    }
 
    /**
     * When this object is created from an unserialization this method is called. 
     * It implements the Serializable interface and uses the data from the 
     * serialize() method herein. Since this method overrides the __construct
     * method you should make any accomodations for constructing your object
     * in this method.
     */
    public function unserialize($data) {
        // "Instantiate" our singleton
        self::getInstance();
 
        // Set our values
        if (is_array($data)) {
            foreach ($data as $k => $v) {
                $this->$k = $v;
            }
        }
    }
}
?>

If you build up this object then serialize it, then rebuild it from the serialization, you can see that it remains in tact. Let’s test this by simulating the session array, first creating an array then adding the DummySingleton object to that array, then serializing it:

<?php
// Grab the class
include 'dummy.php';
 
// Get our instance
$o = DummySingleton::getInstance();
 
// Set something into it for testing
$o->setFromOutside = 'What the hell is this madness?';
 
// Make an array of stuff
$a = array();
$a['name'] = 'Robert';
$a['id'] = 23;
 
// Add the singleton
$a['dummy'] = $o;
 
// Serialize it
$s = serialize($a);
?>

The serialized output from this yields:

a:3:{s:4:"name";s:6:"Robert";s:2:"id";i:23;s:5:"dummy";C:14:"DummySingleton":187:{a:4:{s:5:"dProp";s:19:"I was finally built";s:6:"dPropX";s:25:"Nothing to see here folks";s:5:"_prop";s:16:"y u try see dis?";s:14:"setFromOutside";s:30:"What the hell is this madness?";}}}

If you take that string and subsequently load it and unserialize it then inspect it, you’ll see that the singleton object has been restored along with all private properties of it:

<?php
// $s is our serialized string from above
$o = unserialize($s);
var_dump($o);
?>

Output:

array(3) {
  ["name"]=>
  string(6) "Robert"
  ["id"]=>
  int(23)
  ["dummy"]=>
  object(DummySingleton)#1 (3) {
    ["dProp"]=>
    NULL
    ["dPropX"]=>
    string(25) "Nothing to see here folks"
    ["_prop":"DummySingleton":private]=>
    string(16) "y u try see dis?"
  }
}

Since this is, in essence, the process that PHP follows for its default session management it’s safe to say that you can, indeed, store singleton objects in a PHP session. Now onto to bigger and better questions, like…

Why would you ever want to store a singleton object instance in a PHP session?

Javascript, WebKit and ‘closed’

The other day I was playing around with a simple letter scrambler script that I had written to assist my daughter with a birthday party game. The concept is simple enough… enter a phrase, hit a button and the phrase gets “cryptoquoted”, a process where each letter in the phrase is substituted with another letter. One of the things I designed this program to do was hide the input box so that, if you were viewing it on the web, the solution would not be visible to anyone looking at the puzzle. But I also programmed it so that if you click a link, the input box would be revealed. This toggling of the visibility of the input box is simple enough to do. Just add a little jQuery and BAM!, you have a simple revealer.

And this is exactly how this performed until the last time I tried it a couple of days ago. My toggler suddenly stopped working right, but only in Chrome and Safari. All of the javascript was firing in the proper order, and the function I had written was being called but my slider was not sliding. After digging into this a little bit, and doing a bit of debugging, I found out that a variable name I was using the monitor the state of the visibility of the input box was being clobbered in Chrome and Safari. Firefox worked just fine as it always has. The variable name I was using was closed.

// Set the closed flag
var closed = true;
 
/**
 * Toggles visibility of the input box
 */
function toggleSolution() {
	if (closed) {
		closed = false;
		$('#puzzle-key').slideDown();
		$(this).text('Hide solution');
	} else {
		closed = true;
		$('#puzzle-key').slideUp();
		$(this).text('Show solution');
	}
}

When inspecting this code in Chrome Developer Tools, regardless of any actions, events or any other browser interaction, the closed variable always was valued as false. I still don’t know why this is happening, but I do know this is a WebKit issue. And I also know that changing the variable name from closed to _closed solved the issue I was having. Also, as a simple test, without declaring the variable anywhere in my code, I opened up the console on a page without any javascipt at all and, sure enough, the variable was set to the value false.

So if you writing javascript and run across an issue where you are using a variable named closed in your code that always seems to be valued at false, be aware this might be an issue with your browser and simply changing the name of your variable in your code might make things all better for you.

A simple PHP regular expression tester

I love making my own tools for the simple and mundane tasks I face during the day. One of those tasks is the repeated need for testing regular expressions that I am faced with when programming. Yes, there are a multitude of regular expression testers on the web today, and all of them have a laundry list of cool things they do. But none of them are mine, and none of them are necessarily simple. And few of them let you see how they work. So with that, I decided to take one of the many tools I’ve built for myself and offer it here for you.

My (very) simple regular expression is just that… a simple tester that takes a regular expression and a subject string and gives you back your matches as PHP would see them in your application. There is one small bit of robustness (I had to use robustness… the word is just so cool) added to this tester that will allow you to group your matches together (PREG_SET_ORDER) and allow you to include the string position of the match in the subject (PREG_OFFSET_CAPTURE). But that is where the robustness ends the simple kicks in again.

So if you want a simple little regular expression tester, or just want to see how I’ve coded mine, feel free to use my tester for your own needs. Have fun, stay curious and GO BIG.

Simple PHP table maker

A little while ago I was in need of a way to take tab separated data sets and make HTML tables out of them cleanly. Mostly this was from data copied from a spreadsheet, but sometimes copying from web pages or even text documents has brought this need up for me. So in keeping with my mantra of “Why not write a program to do that?” I decided to write a simple HTML table maker that will take in tab separated, structured data and return an HTML table from it, complete with column headings, a caption and a summary (sidenote: I know that table summaries are being deprecated… still, I included it because at the moment they are still in use for pre-HTML5 markup).

So without further ado, I bring you my simple HTML table maker. It isn’t the most robust thing in the world, but it is still pretty neat. Plus? It totally serves my purpose to the tee. So if you don’t like it, why not gank the code for it and make it better?

Simple PHP Class generator

Someone on the Professional PHP Group asked the question yesterday about whether Dreamweaver has a utility to write setters and getters to your PHP classes for you. I know that ZendStudio has this feature and I am pretty sure that NetBeans has it as well.

But as I thought about this, I thought “How cool would it be to be able to take a list of PHP properties and build a class out of that list complete with your getters and setters?”. That’s when my inner nerd took over and I created a very simple PHP Class Generator.

It is not the most robust tool in the world, but if you are looking for a quick way to build out a class of getters and setters from a simple list of variables, this little tool might be right up your alley. I’d encourage you to play with it and see if it can help you. If it does, tell me about it in the comments.

Oh yeah, a major thank you goes out to Jason Memory of Full Throttle Web Solutions for his help and wizardry in all things regex.

ZendCon 2009: Day 3

And so ends the Zend PHP Developers Conference for 2009…

The last day of ZendCon is always a mixed bag when it comes to wrapping things up. On the one hand you, as a programmer, are loving the learning and education and networking and mixing things up with your peers. But on the other hand you, as a regular person, are tired from all the learning and education and networking and mixing things up with your peers (and drinking… and eating… and more drinking). Still, when all is said and done, all good things must come to an end. And so it goes with ZendCon.

Today started out pretty much the same as the other days except we knew we were in for a half day of sessions instead of a whole day. With that we chose the sessions we wanted to attend and headed for our rooms.

Session 0: Design Patterns for PHP developers
This was the second talk of Cal’s that I attended this ZendCon and, much like the first, Cal gave a great presentation on Design Patterns for PHP. Covering the basics of design patterns, he made sure to mention the most important patterns we could use, like Factory, Strategy, Observer, Model-View-Controller, Facade and Singleton. He made the samples very easy to understand and was quick to answer the questions asked of him.

Design Patterns have a special place in my heart as a programmer (I have given talks to local meetup groups about design patterns) and I love how knowing design patterns levels out the disparity between programming languages. Knowing them makes one language for all programmers and allows anyone from any language background to be able to communicate programming concepts and paradigms in a common tongue, if you will. That said, Cal delivered big-time in his talk on patterns. He also inspired me to pursue my ambition of putting together a PHP Design Patterns web site for developers that have not seen, or do not understand, design patterns applied to PHP.

Slide for Cal’s presentation can be downloaded here. (.pdf)

Session 1: Authorization with OAuth
Rob Richards gave a talk about OAuth and the difference between authentication and authorization. He moved pretty quickly into an actual implementation of using OAuth for authentication of a user from an application and, in my opinion, moved a little too fast into too concrete of an implementation. Still, the presentation was very informative and useful for anyone that is thinking of utilizing OAuth as an authentication mechanism.

Day 3 && ZendCon wrap-up
I was a little saddened to see the end of the conference come up so fast. Still, I am glad its over because I can use the rest.

I’m thinking next year I want to see if I can get in on giving a talk. I’d love to present and would love to not have to pay to get into the conference 🙂 . I also think that it would be freaking awesome to have a small group of the guys I have met over the last two hears at ZendCon over to my home for a BBQ or something, though I should probably bring that up with my wife before I even think of doing anything like that (I will honey, I promise 😛 ).

Overall, this year’s conference was better than last years in a couple of ways. First, the subject of many of the talks was NOT scaling. That, in and of itself, made this conference better than last year.

Second, the location was also a bit better than last year, being closer to downtown and all that being in downtown has to offer.

On the other hand, this year’s conference was deficient in several area. First off, the lack of power in the lobby and in the conference rooms was painful. Having a laptop battery with only a 38% capacity made it difficult to attend a session that didn’t have sufficient power.

Secondly, the vendor fair this year kinda sucked. It was nice to have them there, as always, but they didn’t seem to want to interact with people this year. The shirts were awesome and the shwag was also very nice -who doesn’t like free, right? Still, I think having more relevant vendors with more accessibility to relevant and pertinent information would have been nice.

Regardless, I got nothing but love for the organizers of this conference. Specifically, kudos need to go out to Eli White (@eliw) for his incredible support of the conference and attendees, and Keith Casey (@CaseySoftware) for the indescribable work he does on the conference uncon sessions. I cannot wait for ZendCon2010.

ZendCon 2009: Day 2

Yesterday was an amazing day at ZendCon. Lots of talks, lots of information, lots of networking, lots of geekdom. The day was long but very informative and at the end of it I couldn’t wait to get back for today.

Today started off a bit different than yesterday because today I was scheduled to take the Zend Framework Certification exam and my coworker was scheduled to take the Zend Certification Exam. So we got to the conference and camped out for the morning to get some last minute studying in.

As we studied we were joined by Aaron Wormus. I’m not sure why, but when presenters and other people who are widely known in PHP are close by I always feel like I am in the presence of a celebrity. Last year I was like a little kid at a football game, meeting everyone, shaking hands, being excited, enjoying the conference. This year? Well, kinda the same, except I haven’t seen to have as much time this year to find people to meet.

Still, it was nice to be able to spend a couple of hours trying to familiarize myself with the Zend Framework. The exam preparation study guide is 214 pages long, and as of 12:15, when it was lunch time, I had gotten through about 110 page of it. So much for being totally prepared for the exam.

After lunch was over my coworker and I headed to the exam room where we took our test. And wouldn’t you know it… I passed. So now I am not only a Zend Certified PHP Engineer, I am also Zend Framework certified as well. Sweet!

After the certifications were over we were able to get back into the swing of the sessions…

MySQL Server Performance Tuning 101
Cal Evans, filling in for Legaya Turmelle, did an excellent job of describing how to optimize your MySQL server and sent queries to enhance the performance of your applications. Filled with an incredible amount of technical data, this presentation was still a vibrant session that involved the attendees throughout the entire session. And I managed to sneak away two things that will be a help to me as soon as I get back to work:

/* Show all of your global variables */
mysql > SHOW GLOBAL VARIABLES;
 
/* Show your statuses */
mysql > SHOW GLOBAL STATUS;

Both of these can filter your queries by adding a “LIKE ‘%{filter}%'” to the query. Very handy pieces of information.

Architecting Your Models
Matthew Weier O’Phinney gave an awesome talk about architecting models (the M in MVC) and using your models to handle business logic. The logic that was employed was very similar to the Introduction to Zend Framework talk he gave on Monday (kudos for consistency) and covered data access, table/row gateways and service layers.

This is one of those presentations that I would recommend you get the slides for because just the programming practices employed in his presentation make it an absolutely stellar session and one that can only help you as a programmer. [Note: as soon as the links to the slides are posted I will put that link here. Sorry.]

Building Desktop RIAs with JavaScript and PHP
Ed Finkler gave a sweet presentation on taking PHP and Javascript from the web to the desktop in his talk on building Rich Internet Applications. His talk was dynamic, funny, had a couple of well handled snafus and totally captivated the audience.

Using Adobe AIR, Appcelerator’s Titanium and PHP, he built a couple of cool little desktop apps that are driven by server hosted PHP applications. Though the apps were just for example, what you can do with AIR or Titanium, jQuery and PHP is freaking amazing and I can’t wait to try some of this stuff when I get back to work.

Links to his presentation and associated code samples:

Day 2 wrap-up
Sitting here, at the end of the last session, I am overwhelmed with the amount of information I learned in the last couple of days. I am so looking forward to how ZendCon will be wrapping up tomorrow and cannot wait to meet some of the people of I haven’t yet had a chance to meet.