Zend Framework Module Init Script (Controller Plugin)

Well, it’s been a while since I’ve done a PHP update hasn’t it? Well alls well here in CStat, I have a quickie for you folks.

Recently at work I had the need to run a script before every single controller (namely to add a plugin folder to Dwoo) for a specific module that I did not desire for any other modules.

I could have subclassed all my controllers to extend a custom action controller that handled this in the init() method, however I’m lazy so I wrote a quick Zend Controller Plugin to handle this for me.

What it does is grabs the module name from the request object on routeShutdown (the routeShutdown happens after the route has been parsed and the request object has been generated, but before the action controller is instantiated and executed). From there it uses Zend_Font_Controller::getInstance()->getModuleDirectory(...) to grab the literal path to the module directory, tacks on our init file name (in our case “init.php”), and if it exists execute it in its own clean environment.

The init.php file has access to $this, where $this is an instance of the controller plugin (in particular we can do $this->getRequest() inside the init script).

The code is as follows:

<?php
/**
 * This checks the current request module's directory for an initFile (defaults
 * to init.php) and runs it before the controller is loaded.
 *
 * @copyright 2009 Daniel Cousineau
 * @license http://opensource.org/licenses/mit-license.php MIT License
 * @version 0.1.0
 */
class My_Controller_Plugin_ModuleInit extends Zend_Controller_Plugin_Abstract
{
	public static $initFileName = "init.php";

	/**
	 * @param Zend_Controller_Request_Abstract $request
	 * @return null
	 */
	public function routeShutdown(Zend_Controller_Request_Abstract $request)
	{
		$moduleName = $request->getModuleName();

		$moduleDirectory = Zend_Controller_Front::getInstance()->getModuleDirectory($moduleName);

		//Trim the paths and filenames to prevent any problems
		$initFile = rtrim($moduleDirectory,'/\') . '/' . ltrim(self::$initFileName,'/\');

		$this->runInitFile($initFile);
	}

	/**
	 * Run the file in its own cleaned scope
	 *
	 * @param string $_initFile location of the input file
	 * @return null
	 */
	protected function runInitFile($_initFile)
	{
		if( file_exists($_initFile) )
			include_once $_initFile;
	}
}

As always all code I post on this blog is covered under the MIT license.

My Seven Things (Or: Hey look, the cool kids picked me to play on the team!)

I just got tagged by the BAMF Chris Cornutt, creator of the (in)famous site PHP Developer.org to participate in the “Seven Things” blog tagfest.

  • I’m barely 21 years old. For some reason people are always surprised by this. I’m convinced it’s my beard. That and how many 21 year olds ask for money to attend ZendCon ’08 for their birthday?
  • I was a state science fair finalist in 8th grade I did my science fair project on Artificial Intelligence and refuse to release any more details or information on my project. Let’s just say it was an early point in my programming and computer career.
  • I am an Eagle Scout as well as hold my Vigil Honor in the OA. I was very involved with Boy Scouts in my youth (and plan to continue my involvement in the future when time, money, and internal BSA politics allow), grabbing my Eagle Scout, hiking Philmont twice (65 miles the first trip, 110 the second trip), and getting my Vigil Honor in the OA posthumously.
  • I originally came to Texas A&M to be a CG artist (focusing on SFX). I picked A&M because it had a great graduate CG program (called the Viz Lab) and figured grabbing a CPSC with focus on Art at A&M would help out. I still am fascinated by computer graphics, but realized I was more interested in software architecture when I had more fun planning the OOP design of my ray tracer than actually filling in the guts of the ray tracer.
  • I used to play “teacher” with my younger brother. I would come home from school excited about the math and science I learned (everyone yell NERD) and teach my younger brother (3 years younger) what I learned on this badass little chalkboard in my room. I probably should regret this because my brother just showed up to college taking Calculus 3 his first semester (and acing it).
  • I love Psychology. It was my favorite class in High School (aced the AP test with a 5) and my only regret about college is I never had the time to take any psych classes (though Human-Computer Interaction was an awesome class). If I didn’t do my degree in computer science, I would have picked Psychology as my major.
  • I was an avid trumpet player in Highschool. We’re talking top 2-3 chairs, section leader, All State Solo and Ensemble, $2,000 hand made horn, and 7 years playing experience under my belt before I retired.

Now I kinda got tagged late in the game, but I still need to tag some people:

  • Jeff Carouth, a former co worker, recent php|architect contributor, and the first proof that there were developers that were actually smarter than me in College Station, Texas (but certainly not the last :P).
  • Chris Weldon, the man who started/ran the local PHPUG and the man who showed me that Jeff and I were not the only PHP users in College Station.
  • Ben Floyd, a really great developer I’ve had the pleasure of meeting through refreshBCS. Though he’s primarily a .NET developer (with some serious skills, the Texas A&M Campus Maps site is basically all him), he has done some PHP projects (and even though he gritches about it, I know he’s enjoyed working in the language, even just a little bit).
  • Ben Burket, I would like to see him blog again (he’s another friend I meet through refreshBCS), he’s “my ruby friend” (but a merb developer, noone throw lettuce). I poke fun at his language, he pokes fun at mine, and we both meet at the middle with python.
  • Andrew Ellis, a former coworker who is a security guru. No doubt he will exploit some obscure vulnerability in wordpress to take down my site for tagging him.
  • whurley, the “hey look I know someone famous” friend who’s been exceptionally nice to me. The guy’s an evil genius and he scares the crap out of me, but hey, you only get better playing a smarter opponent. I don’t know if he’ll ever see this or have time to post, regardless you should follow this link and read his stuff.
  • “Henrick”, I read his blog and he posts regularly with some pretty interesting stuff. I have no idea who he is and now officially call him out!

And, of course, the rules to pass on:

  • Link your original tagger(s), and list these rules on your blog.
  • Share seven facts about yourself in the post – some random, some wierd.
  • Tag seven people at the end of your post by leaving their names and the links to their blogs.
  • Let them know they’ve been tagged by leaving a comment on their blogs and/or Twitter.

MiniBarBCS in Bryan, Texas THIS FRIDAY (November 14th, 2008)!

This is a post to make sure anyone interested in development, design, or new media entrepreneurship shows up to MiniBarBCS this Friday starting at 5pm. The event is being held on the 5th floor of the Varisco Building in Bryan, Texas (219 N. Main St., Bryan, TX 77803).

So far the proposed topics cover everything from iPhone development to “Design for Developers” to .NET to PHP, Ruby, Coworking, and anything else under the sun.

So if you’re around the area this Friday, show up and join in the fun! Just make sure to RSVP in the wiki linked above (the password/invite key is “c4mp”) or the Facebook event.

Ubuntu Linux slow/bad internet connection problems

At my office I had been having a problem with my Ubuntu and Fedora boxen having problem connecting to external sites. Some would work, albeit slow, where as others would not work at all (e.g. trying to connect to reddit in Firefox would get enough of the page to display the <title></title&gt tags but it would be “forever loading” the actual content, with only a white screen).

The solution seemed to be that the router hated TCP Window Scaling. The fix that so far seems to work is to edit your /etc/sysctl.conf file and adding the line:

net.ipv4.tcp_window_scaling=0

And then running the command:

sudo sysctl -p

To reload the changes.

Serialize Python Variables To PHP

So I’m in the planning stages of a project where I’ll probably be doing some heavy lifting in Python and serving up the output through PHP. Obviously this will entail transmitting data between Python and PHP and while I haven’t had a chance to do performance testing to see if it’s worth it to save to a database, the only other option was to serialize the data to a file that PHP could parse quickly. Obviously, the output from serialize() is going to be the fastest way to recieved the data.

While there already exists a Python set of classes that serializes (and serializes) Python data, it (a) didn’t handle objects and (b) was licensed under the GPL (rant to follow later), meaning I couldn’t use it for it’s intended purpose due to the closed source nature of my project.

I decided this was a good enough time to play around with git so I created a github repo here.

It could probably still use some more TLC in the object area, maybe a few more supported types, and unserialization functions would be nice.

I do feel it wasn’t bad for a few hours of hacking if I do say so myself.

The code for the module (should be in a phpserialize.py file) is as follows:

Continue reading Serialize Python Variables To PHP

PHP Bacon!

Unfortunately, Elizabeth Smith mentioned on twitter that PHP 5.3′s new garbage collector is based on a paper written by a man named Bacon (pdf here). We now have Bacon’s garbage collector…

Announcing PHP 5.3: Now With More Bacon!!

Spread the meme.

Outputting CSV as a Downloadable File in PHP

Nearly every application you could write in for the business sphere in PHP probably requires some sort of data export, most likely in the CSV format.

The easiest way to provide a downloadable file is by altering the headers and echo’ing the file content. In our case:

<?php
header("Content-type: text/csv");
header("Cache-Control: no-store, no-cache");
header('Content-Disposition: attachment; filename="filename.csv"');

We want to set our applicable Content-Type so that the browsers associate the file properly. Just relying on the extension doesn’t work, even in Windows. The magic is in the third header setting, “Content-Disposition,” which informs the browser to download as a separate file (don’t open a new window and display a blank page, just display the file download box) and tell the browser the filename is “filename.csv”. This way rewrite rules like http://localhost/export/csv/ will result in a download box that declares the file “filename.csv” rather than a randomly assigned name or whatever the current url is.

Into the meat of the CSV export. At the very beginning we need to open up a stream to the PHP output (the same place where echo sends its string content, which is NOT stdout):

<php
$outstream = fopen("php://output",'w');

Next we’re going to assume you already have your data packed nicely into an array (or array of arrays) so long as we have a single array per row/line.

The magic comes into play using the build in PHP function fgetcsv(). fgetcsv() takes an array for a single row and outputs it, automatically escaping output according to column and enclosure delimiters!

fgetcsv() requires a file resource as its first parameter and the magic of PHP streams is they act like a file resource (actually a file resource is just a file stream), so we give it $outstream to make fputcsv() echo its output. We fill in the rest of the parameters according to the php.net documentation and voila we have:

<php
header("Content-type: text/csv");
header("Cache-Control: no-store, no-cache");
header('Content-Disposition: attachment; filename="filename.csv"');

$outstream = fopen("php://output",'w');

$test_data = array(
	array( 'Cell 1,A', 'Cell 1,B' ),
	array( 'Cell 2,A', 'Cell 2,B' )
);

foreach( $test_data as $row )
{
	fputcsv($outstream, $row, ',', '"');
}

fclose($outstream);

For more output stream craziness, Timothy Boronczyk from the #phpc IRC channel on freenode shared a code snipped that outputs CSV either to the output buffer OR will return it as a string using some clever streams hackery:

<php
function exportCSV($data, $col_headers = array(), $return_string = false)
{
    $stream = ($return_string) ? fopen ('php://temp/maxmemory', 'w+') : fopen ('php://output', 'w');

    if (!empty($col_headers))
    {
        fputcsv($stream, $col_headers);
    }

    foreach ($data as $record)
    {
        fputcsv($stream, $record);
    }

    if ($return_string)
    {
        rewind($stream);
        $retVal = stream_get_contents($stream);
        fclose($stream);
        return $retVal;
    }
    else
    {
        fclose($stream);
    }
}

ZendCon08 Wrapup

So I kinda had a thing going about blogging during ZendCon but lost it, so I might as well just do a single day wrap up.

So ZendCon turned out to be completely worth it, even if only for the chance to meet in person a lot of the core PHP community and then drink semi-copiously with them.

The talks were good, though most of them were either more basic than I would have liked or really indepth (/me thinks back to Sara’s PHP Extension Writing talk, though that was more “few php developers gets this deep” than indepth/complicated).

The uncon was nice, which of course I’d like it given my love for barcamps, refreshes, and generally community driven and adhoc events.

The Yahoo party started out awkward given that one expects an open bar after paying $500+ for tickets to a conference, however from what I gathered it really wasn’t so much Yahoo’s fault more the hotel’s. I won the raffle for the “Day with Rasmus” prize and felt bad ’cause when one of the Yahoo girls came to me and to have me verify my information, I told them my email (which was a gmail account) was correct but if they still have trouble to just google my first and last name since I dominate the first page for my name.

My only problem with ZendCon is that it ended…

refreshBCS October 1st

Since it isn’t up on refreshbcs.org yet I’ll repost the announcement from the listserv:

Where: Murphy’s Law (upstairs) [Google Map]
When: October 1st 7PM (Happy Hour starting at 5)
Speaker: Michelle Greer

We’ve been quiet for a while but it’s time to get this show back on the road. We’ve got several months worth of great speakers lined up and we’re starting this thing off with a bang. Michelle Greer has been kicking ass and taking names in the Austin area for quite some time and she has no plans to stop anytime soon. Come listen to her speak about how she uses social media to institute real-life change in the world around us.

Making Social Media Matter:
How Social Media Turns Everyday Citizens into Superheroes

In an age where anyone can publish anything for the cost of hosting a WordPress blog, the means for spreading ideas has never been easier or cheaper. Learn how people have used social media to mobilize people at rates never seen before in history, and how these tools make it easy for you to bring about positive change for your community.

-> Michelle Greer
-> Web Marketing Strategist
-> http://www.michellesblog.net
-> 512.294.3909

If any of you happen to be around college station on the 1st of October, or can make it, I highly suggest you show up to the refresh meetings. Even if the particular topic isn’t your cup of tea (if you are a developer and it’s a design topic, etc.) it’s a great place to connect with people (obviously from the BCS area) and get educated on the happenings on the other side of the fence.