Aug 07

CakePHP RC2It has been a while since I’ve written much about CakePHP (let alone anything on my blog), but I thought I’d update the world with my latest thoughts in case anyone was interested.

I’ve come a long way since I first started using CakePHP.  In fact, I’ve now used the product on some fairly high end sites and had really good luck with it.  There have been minor quibbles here and there (still revolving around documentation mostly), but I’m now a solidified “Baker” through and through.

I will save you some time looking elsewhere and reading the reviews about all the different PHP frameworks; use CakePHP, it’s the best.  In my humble opinion, the only better framework available is Ruby on Rails (which I’d also highly recommend); but if you are stuck using PHP – CakePHP is your best bet.

This framework will encourage (and teach) you to follow through with good web development habits.  These skills are both in programming style (using standardized naming conventions, proper variable scope, documentation, et cetera), but also in technical areas as well (proper database modeling, mvc  code separation, secure user input validation and cleaning, and efficient function development).

Now that I understand the majority of the tenants of Cake, I can say with confidence that it’s a quality product.  1.2 RC2 solved almost all of the minor/major problem I had with the framework and it seems stable as all get out.  Cake will help you use fast, efficient, and complex SQL queries without a sweat.  It will allow you to create fancy “web 2.0′ esque” sites using AJAX and fancy doo-dads with ease.  It will easily validate your input data without the need for you to much of anything.  It provides easy ways to offer web services, shell scripts, and test your code quickly and easily using SimpleTest.  …And that’s just scratching the surface.  The other advantage is it’s super easy to pull in outside code into your projects using components and helpers.  The framework is rigid where it needs to be and flexible in the areas that are key.

In simple terms – “Cake Saved My Life“.

So How Do I Learn It?

You need to learn the basics of PHP first; I think this writeup is an excellent starting point (though I wouldn’t recommend wasting any time with the Zend framework).  I’ve seen a few people on the web talking smack about CakePHP, when the problem was that they really didn’t understand PHP.

Once you have mastered the basics of PHP, go to book.cakephp.org and read the whole thing on version 1.2 of Cake (currently RC2); don’t waste your time learning 1.1.  You can read it in just a few hours and you don’t have to understand it all at that point.. just try to grasp the basics.  If you’ve never worked with the MVC design pattern, then read those sections over a few times until you get it.  Then, install it using the specific directions in the book (read it carefully).  Now is the time to start using Apache2, MySQL, and PHP 5 if you aren’t yet.  I don’t care if you are Windows, UNIX, or Mac… use the products that are the most popular and you’ll make your life easier.

After you get it installed, make up a wild test application in your head and sit down and code it.  Don’t worry about making it pretty; just learn how to code it right.  Learn how HABTM’s work, learn how automagic form validation works, learn the ajax helper details — learn it all!

So to review:

Dustin’s tips to mastering CakePHP:

  1. Learn PHP (Don’t waste your time messing with Zend though)
  2. Read The Book (learn version 1.2)
  3. Install It (Use Apache2, a recent release of MySQL, and PHP 5… no matter what OS you are on; break your IIS addiction or PHP 4 addiction NOW)
  4. Create a test site in your head and finish it within a reasonable time frame.  Force yourself to finish it.
  5. Love it

Almost every problem you’ll come across should be answered in the CakePHP book now; so no excuses for not being able to get it going.  If you have configuration problems, make sure you search through the Google Group; it’s a vastly helpful resource.

Also, don’t forget to look through the Bakery, you can find a ton of code in there to help you solve common problems.

Oct 09

Content Management SystemI’ve had a slew of requests lately from clients needing small web sites they can manage themselves (mostly small businesses).

Truthfully though, I simply prefer the client to manage their content themselves; so essentially we are looking at content management systems (CMS). I’ve had some mild success with CakePHP using my own “home-brewed” CMS for a few sites (thanks for the help Arthur). It works pretty well, but I keep wondering if I’m just reinventing the wheel by building a CMS myself.

So, after weighing the options, here’s my general winner/loser comparison:

Admin Interface Flexibility

  • Home-Brewed CMS
    • I can create an extremely simple administrative side, one that is logical for the client. This allows me to create a dynamic and powerful site, but still allow the client to manage it. I think this aspect is extremely important and often-overlooked in most CMS’s.
  • Open-Source CMS
    • Most of the good ones have too many features for the average client I see. They tend to allow extreme flexibility on the public side of the site (obviously important), but there is little or no flexibility on what admin functions are available. Basically, I need something that is simple to administrate, but has “advanced” options hidden away somewhere. It’s great to have a lot of complex configuration settings for design and administration, but not if that means the client will be calling me every day for help adding a new employee.
  • Winner: Home-Brewed CMS


Relative Costs

  • Home-Brewed CMS
    • It will certainly take some time to develop this product fully on my own. Calling this time “free” isn’t particularly accurate when my time could be spent making money in other ways. However, doing it on my own does guarantee I won’t ever run into any licensing or “upgrade pricing” issues in the future.
  • Open-Source CMS
    • Free (mostly GPL) and generally easy to resell. There might be some issues with licensing in the future, but for the most part, pretty doubtful.
  • Winner: Open-Source CMS

Learning Curve

  • Home-Brewed CMS
    • Obviously becoming a relative expert of my own software is a fairly easy goal. However, the other consideration is the effort required for my graphic designer to adapt to my CMS. In general, it probably wouldn’t be much of a concern in a home-brewed situation (because I can be flexible).
  • Open-Source CMS
    • Certainly a learning curve involved in becoming an expert. Knowing how to install & configure the CMS properly is one aspect, but I’m much more concerned about digging into the code. If I have an issue and I REALLY need it solved, it might be nearly impossible for me to figure out how to solve it quickly. On top of that, it’s likely the templating system the CMS uses would have a bit of a learning curve for my graphic designer.
  • Winner: Home-Brewed CMS

Testing, Security, And Debugging

  • Home-Brewed CMS
    • It’s extremely important to plan for and spend a considerable amount of time testing and debugging. In fact, on most projects, I spend a majority of my time testing. With that being said, the amount of time it would take me to fully test, debug, and check for holes in my own CMS… well, it would consume my life for a very long time. Even after that, there’s very little certainty that I would’ve done a good enough job. It’s just tough to compete with the experienced developers out there who have real-world ideas on things I haven’t thought of yet.
  • Open-Source CMS
    • A single programmer simply cannot compete with open-source testing and debugging of a project. Multiple configurations, multiple types of hardware, multiple security situations… the combinations are mind-boggling. Plus, these projects are frequented by people who are insanely talented experts in areas such as database design, Javascript, XML, and even PHP. I have a good basis on all this stuff, but these people use their hords of pent-up knowledge to help the project achieve much more than I could have on my own… especially in the testing & debugging arena.
  • Winner: Open-Source CMS

Future Growth (Extensibility)

  • Home-Brewed CMS
    • I just have to face it: my own CMS will require constant maintenance and changes as it grows and evolves over the years. I will be rebuilding it constantly and reworking it to solve bugs, issues, and new features.
  • Open-Source CMS
    • The growth and expansion factor is built-in. New versions will be coming out consistantly and will require little or no work on my part (except for dealing with upgrade bugs).
  • Winner: Open-Source CMS

Extendability

  • Home-Brewed CMS
    • Not quite as easy as it could be with an open-source system. With the except of JS scripts and PHP frameworks, cool new features are going to require blood, sweat, and tears on my part.
  • Open-Source CMS
    • The clear winner. It doesn’t take long exploring any of the major CMS extension pages to realize the immense number of plugins available to achieve almost any goal. In fact, I was almost overwhelmed with the number of choices.
  • Winner: Open-Source CMS

Monetary Viability

  • Home-Brewed CMS
    • This is an awkward issue to discuss, but essentially, I am more valuable and can charge more to develop/use my own CMS. It comes down to billable hours and it just takes more to go with the home-brewed route.
  • Open-Source CMS
    • Yes I know I can still charge the same amount for an open-source CMS, but somehow I just don’t think it will work out that way. Just call it a hunch I suppose, but using a pre-existing system just isn’t as valuable (though I realize that for the most part most clients wouldn’t know or care about the difference). Maybe it’s just my consciense?
  • Winner: Home-Brewed CMS

So, by adding up the wins and losses, it appears that the open-source content management system has won the battle, but by just a hair.

Stay tuned for further articles as I delve into reviewing the major open-source PHP-based content management systems available right currently. I might be proven completely wrong once I really start delving into them again, but I hope that’s just my pessimistic nature.

Sep 27

PHP LogoDid you know that PHP has some pretty powerful type casting functionality built-in? It’s no surprise if you comprehend the roots of PHP (since it’s written in C), but I can’t help but think that casting is an often-missed tool when a PHP developer is trying to ensure data integrity.

Just for a moment, let me define type casting in case you weren’t “in the know”:

According to Wikipedia, “in computer science, type conversion or typecasting refers to changing an entity of one data type into another.

So, in laymen terms, casting is an easy way to turn one type of data into another type. For example: converting a “string” variable filled with essentially text into an integer variable containing the same numbers but now representing a value. This makes it easy to do math with the value of what once was just a random string of characters.

The following cast types are allow in PHP:

  • String – (string)
  • Boolean – (bool), (boolean)
  • Integer – (int), (integer)
  • Binary – (binary) [PHP 6]
  • Floating Point – (float), (double), (real)
  • Array – (array)
  • Object – (object)

So, in the real world, when does casting actually come in handy?
Normally, PHP handles all this stuff automatically behind the scenes. But, as is normal, dealing with MySQL database interaction is something to always take seriously — and type casting can help you out!

We’re going to assume your aren’t using the PDO Prepare statement (though you should be). As a PHP developer, a major part of your job is containing the inherent security risks of user input. It’s especially important when these inputs interact directly with the database.

So, your simplified (e.g. – don’t complain) database interaction code might look something like this:


$id = mysql_real_escape_string($_POST['input']);
$SQL = 'SELECT * FROM table WHERE id = ' . $id;

Call me an overly nervous Ned, but I’d prefer to use the following code:


$id = mysql_real_escape_string($_POST['input']);
$SQL = 'SELECT * FROM table WHERE id = ' . (int)$id;

Did you notice the subtle change? See the ‘int’ cast of the $id in the SQL statement?

This should certainly help to ensure that I haven’t missed any security holes for this query. Some might say it’s overkill, but I just wanted a simple explanation for using casting, so get off your almighty soapbox already.

Anyways, as you can see, type casting in PHP has real-world uses. Delve into type casting a little more and you’ll find a huge number of cases where it can make your code that much more bullet-proof.

So seriously, try out PHP Type Casting.

Sep 08

Javascript Loves XMLRight at this very moment, I had a thought cross my mind. If I wanted to use Javascript to modify XML on the fly, how in the heck would I make that happen?

I think the answer is E4X, which is short for “ECMAscript for XML”. I tried to explain it in my own words several times, but I decided Wikipedia does it better:

“ECMAScript for XML (E4X) is a programming language extension that adds native XML support to ECMAScript (which includes ActionScript, DMDScript, JavaScript, JScript). It does this by providing access to the XML document in a form that mimics XML syntax. The goal is to provide an alternative to DOM interfaces that uses a simpler syntax for accessing XML documents. It also offers a new way of making XML visible. Before the release of E4X, XML was always accessed at an object level. E4X instead treats XML as a primitive (like characters, integers, and booleans). This implies faster access, better support, and acceptance as a building block (data structure) of a program.”

So, a powerful use, suggested here, would be building a form dynamically like this:

var html = <html/>;
html.head.title = “Hello, World.”;
html.body.form.@name = “hello”;
html.body.form.@action = “test.php”;
html.body.form.@method = “post”;
html.body.form.@onclick = “return foo();”;
html.body.form.input[0] = “”;
html.body.form.input[0].@name = “Submit”;

Pretty slick, I must admit. Anyways, I’m willing to bet we’ll be hearing more about this new technology soon as it gains traction in an area that needs some work.

For more information, see this and this.

Aug 21

JQuery LogoAfter stumbling across this article, I was in awe to see what has recently transpired in the world of Javascript libraries/frameworks.  I had recently fell in love with Yahoo UI, but I was truly surprised to see that jQuery has gained remarkable traction in the market.

According to This Google Trend, it has leaped far ahead of even script.aculo.us in raw search volume.  This is a particulary good sign for jQuery.  As search volume increases, so will the number of pages related to jQuery obviously and vice versa.

In my experience, rapidly growing popularity is usually a pretty good sign of success for an open-source project.  If problems exist with the project, usually the overwhelming interest helps to spur on solutions and increase the capability of the product because of the massive interest.  I’ve seen this same trend previously with with CakePHP, an excellent framework alternative for PHP based loosely off of Ruby on Rails.

Regardless, it appears that I will start learning jQuery.  Even if it turns out to lose the “battle”, it can’t help to learn more about advanced javascript without being forced to climb a steep learning curve.

Any truthfully, if this popularity trend continues, I think it’s safe to say jQuery is here to stay.

jQuery.com if interested.

Aug 01

Capistrano LogoIf you aren’t familiar with Ruby on Rails, there’s a good chance you’ve probably missed the proverbial boat on a powerful tool called Capistrano.

Do you ever feel like you’re repeating previous work every time you deploy a new application (or when modifying an old one)?  It’s a process I truly despise for two important reasons:

1) I really don’t like to feel like I’m being inefficient.
2) I hate wasting my own valuable time.

Ok, so 1 & 2 are sorta the same reasons… but you get my point.  A fellow programmer friend (a staunch RoR addict) recommended I try deploying my apps with Capistrano, even if they were PHP.  I had never really thought of that idea, but in reality, it made a whole lot of sense.

Anyways, originally I was going to write up a nice how-to on PHP deployments using Capistrano, but I decided the topic was already sufficiently covered.  It’s a good read and I’ll bet you’ll walk away excited about the amount of time you can save.

No more manual exports or checkouts from SVN again!

So, go check out this write-up at Simplistic Complexity for all the details.

Jul 15

The Future of PHPIf you are a fan of language “X” and think it’s better than PHP, here’s your chance to convince me. After some discussion with colleagues, I’m very interested to find a general consensus as to which web development language (server-side) is the true “future of web development”. My research reveals that PHP is the most popular web development language currently. Even though it’s clear that PHP is widely accepted, how long will that be true? Is PHP dying?

Now please don’t get me wrong, PHP is a great language that I use daily. It’s powerful, widely supported, popular, and pretty darn stable. Recently, I’ve even had even more success with PHP by supplementing it with CakePHP, a powerful PHP framework that makes development a bit more painless.

Still, even with frameworks and new versions of PHP coming soon, how long can the trend last?

Are you wondering why I care so much?

The reasons are fairly mundane: job security, stability, trends, and money.

I value my career and work as a web developer. We (web developers) provide content to the voracious users of the web and I love being a part of the “internet revolution”. I also enjoy keeping up on the latest trends… I tend to prefer being near the bleeding-edge at all times. Why? Because it’s more fun. Also, I’d say that having a grasp of where the future is headed in web development can be very valuable indeed.

Back to my point: I’ve played with a few alternate languages outside of PHP, but I’m not convinced of their long-term popularity… they just don’t offer anything revolutionary. Maybe I’m expecting a revolution that isn’t gonna happen. Or, maybe I missed the revolution boat already.

So, you tell me; what’s the next revolution? Has it even been invented yet?

Jun 23

Perl?Recently at work, a brief discussion with a co-worker about Perl vs. PHP encouraged me to do some “reading” about the topic.

Honestly, I had never really considered that people were still using Perl on a regular basis for web applications in the year 2007.  However, my research quickly proved contrary.  Truthfully, I haven’t touched Perl since I was a freshman in College nearly six years ago, so I suppose I’m a tad out of the loop.

This is what I can say though.  Perl is powerful, I’ve always known that.  See… I admit it, I respect Perl.

However, my life as a web developer is easier with PHP (and associated frameworks) than it would be with Perl, at least in my humble opinion.  In fact, if you consider my recent switch to CakePHP (a powerful & flexible PHP framework), I’d venture to say that I could never get the amount of rapid work, prototyping, and other efforts completed if I was forced to use Perl; no matter how many Perl modules I had access to.

I know it’s not fair of me to say that (since I’m no Perl expert), but still… if you are a die-hard Perl addict, you should take a moment to try PHP for your web applications; and take extra care to try CakePHP.  I’m betting you’ll be blown away by the time you save and the efficient code you generate.

May 07

Addiction - CopyrightedAs a web developer I spend a “small” amount of time in front of a computer. It’s to be expected, right? The other day a friend proposed that I spend too much time in front of a computer! Utterly shocked, that simple statement has been perplexing me ever since.

So, this week, I kept track. The following was my PC usage for Mon, Apr. 30th through Sun., May 6th:

Dustin’s Week – Time Spent At The Computer

Monday – Friday
- Approximately 42 hours for all five days at my full-time web development job.
- At least 23 hours at home (after work) programming, doing the finances, surfing, and gaming.

Saturday
- At least 11 hours, although two of that was at my friends house playing XBOX (that counts as a PC, right?).

Sunday
- At least 7 hours after church working on side projects and battling my buddies on BF2.

That’s a grand total of 83 hours this week. Not too shabby. ::pats self on back::

Tonight, I Googled the classic symptoms of a computer addiction and immediately found this article. Dr. Maressa Hecht Orzack listed these highly interesting psychological symptoms of computer addiction.

The 7 Symptoms of Computer Addiction

1) “Having a sense of well-being or euphoria while at the computer”
- Come on now, programming just makes me happy!

2) “Inability to stop the activity”
- It’s a part of my job and it’s fun!

3) “Craving more and more time at the computer”
- If only I didn’t have to sleep, then there would be enough time.

4) “Neglect of family and friends”
- My wife is in law school, she’d rather me be busy than bothering her while studying anyways. My friends… they talk to me on the computer (TeamSpeak)!

5) “Feeling empty, depressed, irritable when not at the computer”
- I’m irritable because it’s inefficient to go camping without internet access and electricity! Seriously, why no WiFi at the campground?

6) “Lying to employers and family about activities”
- This one I would never ever do, I promise.

7) “Problems with school or job”
- How is it a problem? You think my boss wants me to work less? Geesh.

I realize that a ‘supposed‘ computer addiction is also strongly related to a ‘supposedinternet addiction. But that’s a whole other article unto itself and doesn’t apply to me either.

So, if you are a computer addict, please look somewhere else for support. I’m sure there are plenty of other people out there that can help you more than I can.

But me, I’m just fine.

Apr 27

KeysOne of the inherent flaws with any popular web language like PHP is the serious potential of security vulnerabilities from improperly set up installations and servers. Although ensuring a secure server installation (whether Apache or IIS) is extremely important, that process is outside the scope of this article.

Instead, I’d like to recommend one simple tool that will should enable you to pro actively plug most “holes” in your PHP setup.

The ironic part about this article is that just a short while ago I thought I had everything “plugged” myself. I had done my reading up on PHP security and felt confident that I had a secure setup. Unfortunately, in an upgrade to a more recent PHP version, I accidentally overwrote my “secure” php.ini from the previous install. This caused one particular web site to be infiltrated by a nefarious ‘hacker’. Fortunately, there was no serious damage and I quickly found the problem.

However, if I had dropped PhpSecInfo onto the server and checked it out before going live, I would’ve immediately known there was a problem.

So here’s how it works: PhpSecInfo is just a single script and a small library that does the work. You simply drop the PHP files onto your server and execute index.php in your browser. You’ll be treated with a nice looking, clean, and easy-to-understand table of security information about your current PHP setup.

There are a mighty large number of security tests performed and all you have to do is analyze the results. Using the highly familiar red, yellow, green color schemes (from stop lights)… you know which tests have failed miserably, which ones you should probably check on, and which ones you can safely ignore. I realize that it’s not the end-all security check-up for a PHP installation, but I think it’s truly helpful to anyone operating a public facing PHP web server.

So, if you’re interested, check out PhpSecInfo from the PHP Security Consortium.

Whether or not you make any changes to your setup, it’s always good to be aware of your vulnerabilities. Oh yeah, it’s also totally free!

Apr 13

cakephp.gifIf you are interested in using CakePHP on an IIS server, you may have experienced a few problems here and there. Mostly, the problems arise when you are trying to integrate Cake with an existing IIS server and PHP infrastructure that is large or complicated.

Regardless, I have accumulated a few tid-bits of knowledge that may save someone an immense amount of head-scratching, so hold on to your hats.

Note: I still think Apache is the preferred server for a lot of reasons, but if you are absolutely locked into IIS, then please read below. If you think you might be moving over to Apache/Linux sometime soon, seriously consider biting the bullet now. It’s sorta like saving for retirement… the more you do early on, the less of a headache it will be later.

Dustin’s Beginner Guide To CakePHP on IIS

I am assuming you have installed PHP properly and have tested your IIS + PHP configuration for correct functionality prior to attempting the Cake install. Installing PHP on IIS is outside of the scope of this tutorial, sorry.

Configuring IIS

I used Windows XP Pro IIS 5.1 for the instructions in this guide. As I roll Cake apps onto different IIS servers and versions of Windows, I’ll be sure to share what I learn in the different environments.

- Make sure that IIS isn’t checking to see if a script exists before executing.

1) Go to your server admin panel, right-click on the web server (ex: Default Web Site) and click on properties.2) Go to the Home Directory tab at the top and click on the Configuration button near the bottom of that page.

3) Find the .php extension listed in the “Application Configuration” page that appears; click on the .php extension and then click the edit button near the bottom of the page.

4) You should be on the “Add/Edit Application Extension Mapping” page: simply uncheck the “Check that file exists” box at the bottom of the page.

5) Click OK, Click OK again, Click OK once more (you should’ve closed all the windows).

6) Now restart IIS (ie: command prompt -> IISReset).

This little process fixes a few problems and was a sort of ‘magic bullet’ for many of my troubles. If you look into how Cake works and what this check box in IIS does, you’ll have a “no duh” moment like I did.

- Double check your security permissions for the Cake folders/files you dropped into your web root. Just remember that something unzipped to the desktop and copied into your Inetpub directory will often have security permissions that will prevent the server from accessing some files properly.

- Remember that the app/temp folder must be writeable by the web server (for caching). That particular problem had me scratching my head once or twice.

Configuring Cake

1) Drop Cake somewhere inside your web root.2) Go to the APP/Config folder within your cake directories. Simply un-remark (‘BASE_URL’, env (‘SCRIPT_NAME’)) at the top of the core.php config file.

You should now have a working CakePHP application inside an IIS environment. I have assumed that “pretty” URLs aren’t of great concern to you. If you absolutely must have pretty URL’s, consider a good mod-rewrite filter for IIS like Helicon Mod-Rewrite. It’s easy to use and configure, lightweight, and free for most users. If you need it, it can be done.

If you have any hints, tips, problems, or suggestions… please contribute by leaving a comment below. I am certainly not the end-all resource here as my experience is limited to a few versions of IIS (I mostly run Apache anyways).

Share your knowledge, and help make CakePHP a viable option for everyone!

Apr 05

cakephp.gifI spent some time working with a few of the “cool” features of CakePHP this week.

I again noted that Cake is a capable PHP framework in ways that aren’t obvious at first glance. In fact, I found myself fairly impressed by their AJAX and Script.aculo.us support.

For the particular application I was working on, a drag & drop interface was going to be particularly handy. Having spent time previously implementing drag & drop interfaces with Script.aculo.us, Yahoo UI, and Rico, I was hoping the process would be a bit easier using Script.aculo.us as an extension on top of Cake and I was pleasantly surprised with the results. I walked away with a functional drag & drop interface in an amazingly short amount of time with very little coding.

Important Note: A CakePHP beginner should be able to get this tutorial working, but I am still assuming that you have a basic understanding of Cake in order to implement this tutorial properly. If, not please see this article to get started.

In this example, we’ll use a very simplified page of widgets that are “draggable” to change their order and save the changes to a MySQL database in real time.

Make sure you have a recent version of CakePHP (I used version 1.1.14.4603). The document root of your web server should probably be set to:

SERVER-PATH/CAKE-ROOT/app/webroot/

Now, you just need to grab the latest stable version of Script.aculo.us (I used v1.7.0 for this example). For my set up, I extracted the files in the following manner:

CAKE-ROOT/app/webroot/js/scriptaculous/lib/prototype.js
CAKE-ROOT/app/webroot/js/scriptaculous/src/scriptaculous.js (and remaining “src” files)

Also, for this example, I used a MySQL database called “widgets” with a table called “widgets” that contained three fields: “id”, “title”, and “order”.

Here’s The Code:
———————————————————-
Widgets Controller
[ --controllers/widgets_controller.php ]
class WidgetsController extends AppController
{

var $name = ‘Widgets’;/** These are the needed helpers **/
var $helpers = array(‘html’, ‘javascript’, ‘ajax’);

/** Implements the index view **/
function index() {
$this->pageTitle = ‘Widgets Index’;

//status message to be used later
$this->set(‘status’, ‘Widget Ordering Succesfully Saved!’);

//assign widgets to view sorted by the ‘order’ field
$this->set(‘widgets’, $this->Widget->findAll(null,null,’order’,null,null));
}

/** Receives ajax request from index **/
function order()
{
//loop through the data sent via the ajax call
foreach ($this->params['form']['widgets'] as $order => $id)
{
$data['Widget']['order'] = $order;
$this->Widget->id = $id;
if($this->Widget->saveField(‘order’,$order)) {
//we have success!
} else {
//deal with possible errors!
}
}
$this->autoRender=false;
}

}
?>

/*
The data comes to your order action in this format:
Array (
[0] => 19
[1] => 16
[2] => 7 )
where the array indexes ([0],[1],[2]) are the “orderings” and the array values (19,16,7) are the actual “id’s” of each question.
*/


Widget Model

[ --models/widget.php ]
<?php
class Widget extends AppModel
{

var $name = ‘Widget’;

}
?>

Index View
[ --views/widgets/index.thtml ]
<?php
if (isset($javascript)) {
echo $javascript->link(‘scriptaculous/lib/prototype.js’);
echo $javascript->link(‘scriptaculous/src/scriptaculous.js’);
}
?>
<div id=”status” style=”display: none;”><?php echo $status; ?></div>

<ul id=”widgets”>
<?php foreach ($widgets as $row): ?>
<?php echo ‘<li id=”widget_’ . $row['Widget']['id'] . ‘”>’ . $row['Widget']['title'] . ‘</li>’; ?>
<?php endforeach; ?>
</ul>

<?php echo $ajax->sortable(‘widgets’, array(‘url’=>’order’, ‘before’=>”Element.hide(‘status’);”, ‘complete’=>”Element.show(‘status’);”)); ?>

———————————————————-

Take special note of the “before” and “complete” ajax helpers to show and hide the status message. Read more about them here under the heading “AJAX”.

And that’s it! You now have a drag & drop interface that will serialize your form data and save it to the database quickly and easily. Isn’t that a little too easy?

A few important side tips:

- Use Firebug to do your debugging. It’s an invaluable tool that you should use if you don’t already.
- For debugging Cake errors, make sure you have debug level 2 set in [core.php] for some additional help.

If you have questions or comments about this tutorial, feel free to leave a comment at the bottom and I’ll do my best to answer what I can. Remember, this was intended to be a basic tutorial with as much elegance as possible while still remaining clear to differing skill levels. I’m also fairly new to CakePHP myself, so feel free to offer suggestions to make the code better!

I was going to offer a zip download of the source code, but I’d rather you type it out or copy & paste– maybe you’ll learn something in the process.

Mar 17

google-apps.gifSo what’s with this new-fangled Google Apps thing?

To me, it initially just seemed like a fancy version of Gmail. However, as I really started delving into it, I was thoroughly impressed.

Here’s the general description from Google:

Communicate…
Give your users Gmail, Google Calendar and Google Talk accounts that
use your own custom domain, helping them to stay connected and work
together more effectively.

Collaborate and publish…
Docs & Spreadsheets lets users share files and collaborate in
real-time. The Start Page is the first place your users will look to
preview their inboxes and calendars, access your essential content, and
search the web.

…and get on with business.
It’s all hosted by Google, so there’s no hardware or software to
install or download, and minimal setup and maintenance. You can get up
and running quickly, even if you don’t have technical resources.

To try it out for myself, I moved all the email accounts for my web development business to Google Apps Standard Edition. I have to admit, the changeover worked flawlessly. All I had to do was verify my domain by uploading a file to my server. Once verified, I was able to get the email moving to Google’s servers with a few simple MX record changes (and as far as I know didn’t miss one single email in the process). Soon after, I created some additional CNAME’s so I could access the calendar, document, and start page functionalities a little easier. Once those few things were done, I tinkered around with some of the admin controls in Google Apps, but for the most part, the process was complete. It all worked amazingly well.

I am totally sold on this system. I think this new offering will change the way many small, medium, and large businesses handle their communication infrastructures. The real advantages come with the Premier Edition of the service. The most important additions are as follows:

- 99.9% uptime guarantee for email
- 10 GB of space (and I suspect that will grow in the future)
- No ads in emails
- Conference room and resource scheduling
- A very poweful API system (including custom sign-on, authentication, user provisioning & management, and support for email gateways allowing backups of data).
- Email migration tools (in the works)
- 24/7 support via phone/email
- A variety of 3rd party applications and services to enhance the system
- Extremely low-cost ($50/user/year)

Yes, the amazing email client is incredible with it’s spam filtering, organizational ‘labeling’, and search functions, but the other tools included are the pieces that will create an evolution in how businesses operate (in my humble opinion):

- Imagine having the ability to have incredibly powerful calendar/scheduling tools without the hassle and complexity of expensive Exchange servers.

- Imagine being able to only allow certain groups of people (or individuals) to see certain calendars and events in real time, with just a few simple clicks.

- Imagine having a chat client integrated with your system that allows quick and effortless communications instead of picking up the phone or waiting on email responses. What if this client was embedded throughout the system and all communication could be archived and saved for security/legal purposes? What if that chat client also allowed voice calls to be made for free over the internet?

- Imagine being able to collaborate on documents or spreadsheets with teams of users all in real time over the web. What if you could publish these documents for only certain members of your organization to see? What if they could be saved in popular document and spreadsheet formats for desktop editing?

- What about a very powerful, yet simple & easy to use corporate start page that has important information customized for each particular employees’ job functions and can be easily branded?

- What if your users could access this data anywhere in the world with just a browser? No more need for VPN’s (to access email securely), Outlook clients, software updates, et cetera.

- What if the majority of these systems integrated with wireless/portable devices like BlackBerry phones with little-to-no effort?

- What if this entire system was simple to administrate for even the largest of companies? You would hardly need one employee (at most) to manage the system. No exchange server experts needed ever again (sorry guys)!

- What if this amazing system was hosted in some of the most secure and reliable data centers in the world (Google’s) and optimized for world-wide use? No more worrying about expensive hardware, licensing, storage, bandwidth, replication, or down-time concerns.

- What if there were a plethora of 3rd party and advanced packages allowing custom email gateway services, archiving, security, authentication, et cetera?

It’s all available right now!

So go and check out Google Apps Enterprise Edition… no matter what your company size, it has the potential to save your company time, effort, and vast quantities of money while increasing productivity and profit. Seems like a no-brainer to me.

Mar 08

http-pipeline.gifDefined here by Wikipedia.org, “HTTP pipelining is a technique in which multiple HTTP requests are written out to a single socket without waiting for the corresponding responses.

Mozilla talks a bit more about the topic: “Normally, HTTP requests are issued sequentially, with the next request being issued only after the response to the current request has been completely received. Depending on network latencies and bandwidth limitations, this can result in a significant delay before the next request is seen by the server.

I have accepted the fact that HTTP pipelining is pretty much disabled in all modern browsers, but that doesn’t mean I have to like it!

I have a widget in Firefox that allow me to bypass this missing “feature” and it sure seems to speed up my browsing quite a bit. However, why can’t everyone get together and work this problem out so we don’t need extensions/widgets/hacks to get around the limitations?

I attempted to harass Microsoft about it and never received an answer (I didn’t really harass them per say). Firefox isn’t mum on the subject (here), but it seems to come down to compatibility issues with certain servers, routers, et cetera in some specific cases (even if the HTTP/1.1 spec allows it).

So what does a web developer do (programmatically)?

Do we just accept the fact and move on or is there something we can do about it? How can we speed up our page loads to a world that can’t use pipelining?

It turns out there is a relatively simple way to “fake HTTP pipelining”. When I read through the article “Optimizing Page Load Time“, I had a very revealing moment of self-inflicted-disrespect. The solution is so obvious, but it never dawned on me previously. Why not simply source content on the page from different locations? It doesn’t even have to be different servers, just different domains. Pretty simple right?

For example, we could do something like this for a single web page:

- Static Images: images.dustinweber.com
- Javascript Includes: includes.dustinweber.com
- CSS: css.dustinweber.com
- Static Content: static.dustinweber.com
- Dynamic Content: dynamic.dustinweber.com

Now this is a pretty extreme example that I wouldn’t recommend for production (except in very specific cases), but let me explain what happens in simple terms. Instead of your browser making a request to one domain for all the content, data, files, and everything for a page; it splits up the requests amongst the various sub domains (of which could be hosted separately or together).

What does splitting up the content get us?

The advantage is that the browser isn’t sitting around waiting on previous requests to complete before moving on to the next item. It really only makes sense for larger pages. In fact there is a drawback, according to Aaron, “Beware that each additional hostname adds the overhead of an extra DNS lookup and an extra TCP three-way handshake. If your users have pipelining enabled or a given page loads fewer than around a dozen objects, they will see no benefit from the increased concurrency and the site may actually load more slowly. The benefits only become apparent on pages with larger numbers of objects. Be sure to measure the difference seen by your users if you implement this.”

Perhaps now you can consider playing around with this idea a bit on your own. Given plenty of tinkering time and careful examination, it could help decrease page load times noticeably.

If you’d like some more tips on this subject, check out Optimizing Page Load Time.

Mar 07

consumer-testing-labs.gifI realized the other day that I haven’t really talked about my employer, Consumer Testing Labs, all that much.

So, what is it that we do?

Let me quote from our web site so I get it correct: “Since 1952, we have been helping quality conscious retailers and manufacturers ensure the quality of the products they sell and by doing so protect their business and their most important asset–their customers’ continued patronage.”

Basically, we help out the consumer by ensuring quality products are on the shelves and the retailer by ensuring they don’t sell products that will be returned frequently or are hazardous to the health/safety of their customers. Not only that, but we do it faster, better, and cheaper than the competition!

With all that being said, let me explain why it’s a cool company. I have to openly admit that our testing laboratories are really hypnotic (interesting) places to visit.

We have a world-wide presence in three major categories of testing:

1) Food — essentially anything edible
2) Softlines — essentially anything you wear
3) Hardlines — everything else (yes, a massive category)

On my initial interview with the company, I received a first-class tour of the Food Labs located in Bentonville, Arkansas. I can truly say that the food testing process is awe-inspiring. The employees who test these food products are highly skilled and the testing procedures they go through are rigorous, complicated, and highly accurate. They use machinery and test equipment in the lab that I swear I’ve only seen in Star Trek episodes. But outside of the cool equipment, even the simple taste-testing area is neat.

Truthfully though, the Hardlines lab is my real favorite. Can you imagine how fun it is to test the break strength of steel cable? Or to see how many tons it takes to cause an industrial shelving unit to collapse? How bout checking the electrical bleed tendencies of high power air conditioners? You can imagine the fun when it comes time to test barbecue grills! It’s a really fascinating place that is always buzzing with activity, huge machines, and strange noises. Every time I go there, at least one test-in-progress captivates my attention for a lengthy time (usually only as long as I’m allowed to stand there gawking). I’m just skimming the top here, but I think you get the picture; it’s a cool place.

But even the Softlines Lab has neat stuff going on. Fiber analysis, color accuracy testing, & children’s sleepwear flammability testing just barely touches on all the interesting testing that occurs there.

So yeah, basically, it’s a pretty unique place to work.

As a web developer, I don’t get to see all the testing that occurs every day, but my job is to enable the testers and the company itself to achieve goals more accurately, efficiently, and faster by leveraging existing technology and creating new technology where it fits.

The employees at Consumer Testing Labs have a lot of pride in their work and although I don’t get to blow stuff up on a daily basis, I really enjoy the fact that my efforts enable our employees’ hard work to pay off even more for themselves and the company as a whole.

If you have any interest in working for us, please check out our job openings (and tell em’ I sent ya). We always seem to have new jobs available as the company keeps growing and growing.

In the mean time, just remember that we might’ve tested that chain saw you use every weekend or that piece of cheese you ate last night; so feel free to silently thank us that neither one killed you!