CakePHP Book and Code Updates
The Book
For anyone who missed it, I released a free CakePHP book a month ago. Since then it's been downloaded over 2500 times. I've also received some great feedback and have made a bunch of corrections to the code and grammar. The biggest change is that the table of contents is now links and will jump you right to the section. That's reason enough alone to grab the updated version. The new permanent home page for the book is here.
Interactive Console and DebugKit Panel
Github Link
http://github.com/mcurry/interactive
Updates
I fixed a couple issues that were pointed out in the comments of the announcement post.
One of the suggestions was to have the up arrow cycle previous commands when using this in the console. It's a great idea and actually works magically on ForTheWindows. I checked it out and I didn't see a way to make it happen for all systems though. So, I did the next best thing. Hitting enter on a blank line re-runs the previous commands. Entering 'h' brings up a list of the last 20 commands and you can run one by just entering the number. Command history is also saved across sessions, so you can exit and go back in and still run old commands.
Custom Find
Github Link
Pagination
I pulled in some of the ideas from Daniel Salazar's post and now the custom find types have built in pagination support. It's kind of scary how easy it is. Here's an example:
$this->paginate = am($this->paginate, $this->Post->find('published', array('paginate' => true)));
$this->set('posts', $this->paginate());
This only works if you are still using one of the default find types to run the actual query, as opposed to Model::query();
Extending Model
I struggled with how to make this plugin easy to install. I didn't want to force people to have to copy and paste a bunch of code into their AppModel. I felt like that would make updates harder and would just make AppModel too messy. So instead I recommend that you have your AppModel extend FindAppModel instead of Model. FindAppModel in turn extends Model. Multiple inheritance would come in handy here.
Ajax Chat
Github Link
Updates
A couple small changes here. The helper now handles cake installs that aren't running in webroot automatically, so you don't have to set it in the JavaScript manually. Also the posted chat message now appears instantly in the chat window. Before you'd have to wait for an update for the message to appear.
Asset
Github Link
http://github.com/mcurry/asset
Updates
The order that scripts and codeblocks is now maintained. The previous version always put codeblocks after scripts, but there are times when the codeblock needs to go before a script. The new version keeps everything in the order that it was entered. This means if you do script1, codeblock, script2 that the two scripts won't be merged because it is assumed that the codeblock is dependent on script1 and script2 is dependent on the codeblock.
JS Validate
Github Link
http://github.com/mcurry/js_validate
Updates
I merged a couple changes from javierm's fork. These include a fix for the numeric check, matching Cake's default error HTML and including the fieldName when calling custom rules, which should make doing Ajax validation much easier. I'll have a post showing some examples of this next week.
Interactive Plugin For CakePHP Console and DebugKit
I teased this on twitter last week, so here's the official release. The interactive plugin is a super easy way to run code against your Cake app. You can use it either through a custom panel in the DebugKit or from the command line as a shell.
Download
Instructions
I'll skip the install instructions, since they're included in the README. It's pretty easy to install. If you're using the latest stable release of the DebugKit you do need to apply a patch for better plugin handling. That fix is already in the trunk, so it's not a dirty hack.
What It Can Do
Let's get right to the good stuff.
Run Simple PHP
Pretty much any simple PHP commands will run:
10 % 4 //returns 2 is_array(49) //returns false
Run SQL
SELECT id FROM users WHERE email = 'test@test.com' //returns the id of the user UPDATE posts SET published = false; //returns "No results found.", but does the update.
Use Cake Functions
__('Test Message', true) //returns the translated text matching the msg id for your current language.
Configure::write('Config.language', 'es');
__('Test Message', true); //returns the translated text in Spanish.
Use Cake Libs
Security::hash('my_pAssw0rd', null, true) //returns the hashed password
Set::extract('/id', array(array('id' => 3), array('name' => 'test', 'id' => 4))) //array(3, 4)
Use Cake Helpers
$html->link('Posts', array('controller' => 'posts')) //the html code for the link and the link itself
$form->input('Post.title'); //the html code for the field and the field itself
Use Your App Code
Post::find('first') //The first record from your posts table
User::findById(3) //The user record for id 3
Debugging
If you have a command that isn't returning the results you expect, you can turn on debug first:
Configure::write('debug', 2);
User::findByIdd(3) //will show error output
Notes
When using through the DebugKit you can stack commands, just separate them with a ";". However you can't define a variable in one command then use it in another. For example this doesn't work:
$i = 10; $i ++; echo $i;
You'll also notice I never explicitly declared any of the models I was using. The plugin does this automatically. You can write your model calls statically or just pretend you have an instance. These are all the same and will work:
Post::find('first');
$Post->find('first');
Post->find('first');
$this->Post->find('first');
The DebugKit = Awesomeness
Like most of you, I read this post from Mark Story on the new JavaScript for the DebugKit. Just reading that post, you don't get a full appreciation for how much work he (and others) have put into it. The JavaScript lib is virtually it's own mini-framework. Everything I needed to create this was already included - Ajax, Event handing, Elements...Really great stuff.
That's About It
Let me know if you hit any commands you want to run that aren't working. I tried to cover most of the basics.
Movie Review: Star Trek
Preface
I'm going to be in the minority here, but I really didn't like the new Star Trek movie. It's currently at 95% on Rotten Tomatoes. Wow! Really? Did I see the same movie as everyone else? Let's get right into it...
This review is full of spoilers...I don't make any effort to mark them or hide them. Read at your own risk.
In The Before Time
The movie opens with the USS George Kirk investigating a space "lighting storm". Emerging from the storm is a Romulan mining ship from 150 years in the future. Remember this is a mining ship, not a military vessel. It's crewed by SPACE MINERS. A short fight ensues the captain of the good guys ship shuttles over to the mining vessel where, after having some fancy holographs thrown at him, he is IMPALED BY A TRIDENT. Before the Federation ship can be destroyed 800 are able to escape on shuttle craft. Of course the filmmakers gloss over the fact that the shuttle craft have no warp drive. How were they rescued? And why didn't the Romulan ship destroy them all? Was it so badly damaged from the collision? If so how does a ship from the future get repairs? It's not like they can just jet over to Mos Eisley for some body work.
The Childhood Years
It would be a pretty short, but infinitely better, movie if the shuttle crafts had just been picked off by the space miners. Unfortunately, they somehow made it to safety, which leads to a painful childhood Kirk scene. We get that he's rebellious, but also suicidal? And these traits are what Starfleet is looking for in their starship captain aptitude test?
The Academy
Flash forward another dozen years or so: Kirk is now drunken womanizer with no real aspirations. Yet, he conveniently still lives near a Starfleet base and frequently visits bars populated by Starfleet cadets. It's almost pathetic. Like he's waiting for someone to notice him. Eventually Captain Pike recognizes him because he wrote his Starfleet dissertation on the events that killed Kirk's dad. Not only does he recognize Kirk, but he invites him to join Starfleet Academey. This isn't some community college. It's FRIGGIN' STARFLEET ACADEMY. It's like Harvard, West Point, and Google all rolled into one. And Kirk doesn't even have to send an application or references or write a cheesy essay. It's no wonder that everyone hates him. Is that another quality that Starfleet looks for in its captains?
Kobayashi Maru
We all know from Star Trek II that Kirk cheated to "win" the Kobayashi Maru. Basically he hacked (oh come on) the test and made it passable. We actually get to see that scene play out and it's really quite painful. Kirk is completely arrogant and just looks pathetic. I bet he uses an aimbot when playing Counter-Strike. That fucker.
Graduation
Kirk is pretty close to being expelled, but thankfully there is a distress call from Vulcan. The Starfleet Generals must have just finished a two day binge of Police Academy movies, because they get the brilliant idea of sending the cadets to deal with threat. Conveniently, there are undermanned starships just sitting in space dock, including the brand new Enterprise. Logically (for once), Kirk isn't assigned to a ship, but thanks to some quick thinking by Bones he is infected with a strange disease and allowed on board. That's right, there is a Starfleet regulation that allows a doctor (not even the head doctor) to bring a patient infected with a potentially contagious disease on board during a crisis situation.
On The Road
As all the other ships take off for Vulcan, The Enterprise lags behind as young Sulu forgets to disengage the "parking break." The flagship of the Federation has a pilot that is so green he doesn't even know how to go to warp. Is this really the guy you want driving your ship as you head into an unknown situation?
And seriously, Kirk is the only one who figures out what's going on? PIKE WROTE A FUCKING THESIS PAPER ON THE ORIGINAL EVENT AND SPOCK IS A WALKING WIKIPEDIA. But no one, only Kirk figures it out. Even after they all agree, they still don't warn the ships ahead of them or do anything different. And guys it's not a "trap" when the other ship doesn't give a shit if you show up or not. It's not like the mining ship knew exactly where they Starfleet ships would appear and had a photon torpedo storm waiting. They were stuck in a fixed orbit over the planet using the drill thingy.
This kills me about time travel in movies and TV. Why didn't Nero team up with Future Spock and just save Romulus this time around. They had a 125 year head start. This time they could make sure that Young Spock would be waiting with the red matter well in advance of the supernova hitting Romulus.
A couple other points here:
- Would the debris field from six destroyed starships really be that thick? If that section of space was orange juice it would have been labeled extra pulp.
- Did no one from Vulcan bother to send an updated distress call with some details of what was going on. I know, I know: communications were blocked, but are there no shuttles? Couldn't someone have just warped a few parsecs and then sent a message?
- Kirk made the connection that this was related to his dad's death because of the similar "lighting storm". But wasn't that storm caused by the wormhole, not the Romulan ship? Why was the same anomaly detected near Vulcan?
- Where the fuck was the Romulan ship the last 25 years? Did they just hang out near the wormhole waiting for Spock? How did they even know Spock would come through? Was there an astrophysicist on the crew of the SPACE MINING VESSEL?
- Was this crew of SPACE MINERS so hell bent on vengeance that they all just willing waited 25 years? I guess if they have a holodeck it can make the wait bearable...
- Did Starfleet not send another ship to investigate the anomaly?
Are We There Yet
After about a fifteen minute trip the Enterprise arrives at Vulcan and is quickly disabled. Right before Emperor Nero goes for the kill shot he pulls back, because he RECOGNIZES THE ENTERPRISE! I guess with 25 years to kill you can read a lot about Spock, but that's assuming the computers on his SPACE MINING SHIP already have that info.
Pike is forced to shuttle over to the enemy, because space drill blocks transporters and communications when enabled - AS A SIDE EFFECT, not by design. If I'm the head of a space mining company 150 years in the future and I need a drill that can go to the center of the planet and someone comes to me with this thing, isn't the fact that it inadvertently blocks communications and transport a deal breaker? Do they have to knock 20K in gold-pressed latinum off the purchase price because of this?
The brilliant plan that Pike comes up with has Kirk, Sulu and a clearly not going to survive security officer sky jumping off the shuttle (which is probably outside the Vulcan atmosphere) and free falling onto the platform. How about just firing a fucking laser beam at it? Would that have been so hard? Yeah, Nero would be pissed and probably destroy the Enterprise, but that's a pretty fair trade for 8 billion Vulcans.
Predictably, the guy with all the explosives dies after trying to be a hero and deploying his parachute at the last possible moment. (before you comment that this was probably a homage to the original series where the random dude on the away team always dies...I get it). After a SWORD FIGHT Sulu and Kirk fail to destroy the platform and end up falling off the edge only to be saved by Chekov's mad transporter skillz.
Meanwhile...
On the Romulan ship they are preparing the red matter which is a vat of highly unstable and destructive materiel, where one drop can create a blackhole large enough to stop a star that has gone supernova or destroy a planet. They acquired this vat from Spock who was going to use a single drop of it to save Romulus. Why didn't he just bring one drop, instead of a whole fucking keg? That would have been too logical.
The reason the bad guy needed Pike is so that they could extract the code to the Earth defense grid. Oh come on...really? The Earth defense grid is password protected? That's it? Did they at least make the password contain numbers and letters? Plus the Romulan ship has pretty much dispatched all adversaries with ease. They suddenly couldn't get through an archaic (by their standards) defense grid? And why didn't Vulcan have the same setup?
Boom Goes The Dynamite
Spock realizes the planet is about to go boom and is forced to beam down to save the Vulcan elders, because, apparently, they decided a planetary crisis was a good time to have a sacred cave meeting with no access to communications or transporters. Even stranger, Spock's HUMAN mother is with them. Is Spock's mother the biggest wet blanket, ball and chain wife ever? Did Spock's dad try to sneak out for for some good times with the boys and get caught, then was forced to take her with him? I can just imagine the buzzkill when the Spocks enter the cave together. Ugh, he brought her again. Most of you probably didn't catch it, but when Vulcans are getting transported and the cliff collapses killing Spock's mom, one of the Vulcans in the background give a slight fist pump. It's subtle. Also it's convenient that exactly six of them made it out of the cave, since there were only six transporter pads. How great would it have been if seven had made it and they had to tell one of them "we'll get you next time."
This Is Where It Really Falls Apart
Vulcan is gone and Spock now wants to rendezvous with the rest of the fleet. A HIGHLY EMOTIONAL (this is important later) Kirk wants to chase after Nero, who has now has targeted Earth. Why Earth? Didn't he just accomplish his vengeance plan? Spock has Kirk ejected from the ship, where he lands on the ice planet Hoth. Rather then waiting for tauntauns from a nearby Starfleet outpost, Kirk decides it would be a good time for a walk. Is he making the 14 mile trek to the outpost on foot? This is better then just waiting to be picked up? Once again, solid decision making from Kirk. A painful chase scene right from the Phantom Menace/Lucas playbook ensues where Kirk is hunted by some of the native creatures.
Future Spock
Ok, I can buy all the other huge leaps up until this point, but on a deserted ice planet Kirk happens upon Future Spock, who was stranded there by Nero, so he had a front row seat for Vulcan's destruction. Spock apparently knows that there is an outpost on the planet and how to get there, but didn't think to actually go there and try to stop Nero. And why the fuck is there an outpost on this planet? What conceivable reason could they have had?
Wait, It Gets Worse
Spock reveals that he can beam Kirk to the Enterprise, despite not knowing where it is (how could they?) and that it's traveling at warp speed. How does he accomplish this bit of magic? With a fucking formula! That's right. No modifications are needed to the 150 year old transporter technology other then fixing up the code a bit. Scotty, who was conveniently at the outpost, goes with Kirk. First of all if I was Scotty you couldn't drag me off that outpost. You mean I can stay in this nice toasty igloo on a planet completely out of harm's way or I can be the guinea pig for a high risk beam that will likely leave my arm coming out of my forehead and even if I'm lucky enough to survive I'll probably get to witness Earth being destroyed and then die myself when Nero uses his future drilling weapons on my ship. Fuck that, I'm staying here.
Second of all: why the fuck doesn't Spock go? You ready for this? Because he thinks it will be a good bonding experience for Young Spock and Kirk. That's right, Spock risks the fate of Earth, so that the Spock/Kirk bromance can blossom. Wait, get this: for Kirk to succeed, Future Spock tells him he has to become captain of the Enterprise and the best way to do this is to get Young Spock to flip out by bringing up his dead mom. We've already established that Kirk is a pretty big dick, so really this isn't that much of a stretch. The scene would have played out so much better if Spock had said: "To get control of the Enterprise you have to...", then simultaneously Kirk and Spock said "...make Spock cry by ragging on him about his dead mom." Then they high-fived.
The Fight
After another wasted action scene where Scotty gets stuck in a water slide, Kirk and Scotty are captured and brought to the bridge. Why didn't Spock just throw them in the brig? I think even Kirk was surprised; otherwise why did he try to evade the security guys? After a dozen or so "yo mama" jokes Spock finally flips out when Kirk lets loose this gem: "Hey Spock, I think we both have the same lasting image of your mother. The top of her head as she was going down. OH, SNAP!" Spock attacks Kirk, and then decides to step down as captain on his own. Now remember that even though Nero killed Spock's mom and destroyed his homeworld, Spock wasn't going after him. Kirk, whose Dad was also killed by Nero (this fact is now swept under the rug), is gung-ho on a suicide mission to stop Nero. Which one of there two is letting their emotions affect their decisions? If you answered Spock: Hi JJ Abrams, thanks for reading this.
They Kiss And Make Up
Spock runs off to his daddy and they have a heart-to-heart. I'm not sure exactly what was said, since I was trying to burst my ear drums with my soda straw at this point. Spock returns to the bridge and asks for the first officer's job. What a pussy! He just got played by Kirk and now he comes begging for his old job back!
Anyway, they have a new plan to warp into Saturn's belt, then dramatically rise through the space cloud just like in every fan boys wet dream. But then what? Oh, Chekov has figured out a way to beam onto Nero's ship. How fucking timely.
So they're going to beam a whole fucking army on board, right? Just Spock and Kirk? Really? But they'll be double fisting phaser rifles and wearing bandoliers instead of shirts, right? No?
How about this for a better plan: Let's just beam Pike right the fuck out of there, destroy the mining platform with our fricken laser beam, hail Nero and make fun of his dead wife and dead unborn baby so that we can lure him away from Earth and then beam about 400 photon torpedoes over, enjoy the explosion while cranking some Metallica, then go hit the space bar and get some hot green ass? Whose against this plan? Anyone? I didn't think so.
The End...Thankfully
I fucking hate scenes where the good guy has just a handgun and is against fifty bad guys with rifles, but the bad guys can't make a shot for their life and the good guy is running through swarms of bullets making ridicules shots. Don't movie makers play Call of Duty on Xbox Live? It just doesn't work that way.
You can pretty much guess what happens: Kirk rescues Pike, Spock steals back his future ship, destroys the drill and lures Nero after him before engaging in high stakes game of chicken. The resulting collision ignites the GIANT FUCKING VAT of red matter, which should probably engulf the entire milky way galaxy.
Nero's ship is disabled and will soon be destroyed by the ignited red matter and after refusing assistance KIRK OPENS FIRE ON HIM. They should have had Kirk pull on a Judge Dredd helmet and say "I am the law." No one in the Federation was even a little pissed that Kirk didn't capture Nero so he could stand trial - this was virtual street justice.
Aftermath
Kirk receives a medal for his part in the events. Not really sure why. Let's break down what he did:
- Realized that Nero was attacking Vulcan - Result: no change - they still went with the same plan.
- Attempted to destroy the mining platform on Vulcan - Result: fail.
- Took over The Enterprise and went after Nero - Result: success, but only because Chekov figured out a way onto Nero's ship. If Chekov had been about 10 minutes faster and presented his plan why Spock was still in charge don't you think Spock would have turned that ship right around and gone after Nero?
- Rescued Pike - Result: success, I guess. But they could have just beamed him out of there. Plus it was Spock who did all the dirty work here.
- Inspired the crew and earned their respect - Result: epic fail. Kirk did everything he could to get rid of Spock, but that wimpy little bitch kept coming back. He sexually harassed Uhura at every turn.
Oh, and wouldn't you be pissed if you were one of the 12k surviving Vulcans and Earth was having a ceremony celebrating Kirk? 8 billion Vulcans just died. Doing the math, the amount of mourning time is about 65 million years. That sounds about right.
A Few Other Things
I hated how the main characters all rose to their positions. Not one of them actually earned their jobs, except maybe Spock. How would you feel if you were a starship pilot and spent years working your ass off and actually spent time in the field only to see Sulu promoted ahead of you. Way to kill the moral of the entire fleet.
Not sure if you picked it up, but I wasn't the biggest Kirk fan. They really made him unlikable here. I know Kirk is supposed to be brash and arrogant, but they really overdid. He doesn't have one redeeming scene in the whole movie.
You're All With Me Now, Right?
I'm sure some of you will still disagree and that's your right as a mentally challenged member of society. I realize this was supposed to be a "fun, summer movie," but does that really exclude having a decent plot with creative action sequences? I really blame myself because all the warning signs were there in the trailer. I just foolishly ignored them. This is why I only go to the movies once a year.
CakePHP Digest #15 - Blog Posts Edition
In The Blogs
There were a ton of really good blog posts in the last couple weeks, so pretty much this entire digest is going to be blog posts.
Paginating Custom Find Type
Daniel Salazar has a great post on a simple way to paginate over custom find types. It's scary how easy it is and makes it simple to have multiple pagination schemes per model without having to worry about creating paginate and paginateCount functions.
How To Use Bake
This tutorial on how to use bake was hot on twitter. Don't get me wrong, bake is great, but if I'm introducing someone to Cake showing them the command line bake tool isn't the first place I'd start.
Pagination Sort Direction
Richard@Home has a quick post on how to add a CSS class to the paginated columns that can be used for adding a direction arrow. Crazy that this isn't part of the core, right? If you don't want to create a new helper, you can accomplish the same thing using an element applied to the <th> tag.
Styling Flash Messages
James Fairhurst awoke from a six month coma and posted a pair of new articles. The more interesting one is on using layouts for flash messages.
Tips For Using Accented Characters
Jimmy Bourassa has a series of tips on how to successfully use accented characters. His post can pretty much be summed up as: use UTF-8 or fail hard.
Redefine HTML Tags
Flipflops.org has another simple, but extremely useful tip on how to redefine the html tags that Cake uses if you don't like the defaults (see part 2).
In The Wild
dogcommanger.com
From @rsrose: dogcommander.com
Code
Integrating Facebook Connect With The Auth Component
Before I post the link, let me preface by saying don't actually use this code verbatim. You'd be much better served rolling this into it's own component (preferably as a plugin), rather then just putting it all in your AppController. Anyway, here it is.
I'm Out!
And on that note don't forget to subscribe to my feed or follow me on twitter.
As always if you think I missed something leave a comment. Or if you do something interesting and want it included in the next digest, send me an email.
Connecting CakePHP Plugins
Today I wrote a CakePHP plugin for localizing JavaScript files. Basically it allows you to use the translate convenience function, __(), in your JavaScript files and will cache the results so that the static file can be used on all subsequent requests. Way back I wrote an asset plugin that combines and compacts JS and CSS files automatically. I thought it would be cool if I could get the two plugins to work together, so that if they were both installed a localized, combined, and compacted JS file would be returned to the user.
Here's The Trick
In the asset plugin I needed to know if the localization plugin was also installed and if it was use it. Cake's App::import() function returns "boolean true if Class is already in memory or if file is found and loaded, false if not." Perfect. I moved the majority of the localization plugin code to a model, JsLang. Then I can simply do:
$this->Lang = false;
if (App::import('Model', 'Js.JsLang')) {
//plugin is installed.
$this->Lang = ClassRegistry::init('Js.JsLang');
}
From there I can simply check if $this->Lang is not false and then use it for added functionality.
Beta Warning
It's pretty late and I'm programming on fumes, so assume that something is messed up somewhere. Both plugins have pretty good test coverage, but that doesn't mean I didn't fuck something up somewhere.
Plugins: USE THEM
If you plan on releasing ANY CakePHP code, do it as a plugin. There isn't any reason not to. Even if it's the simplest of helpers, it's worth it just to be able to provide unit test coverage.
