• RSS
  • Email
  • Twitter

CakePHP Digest #12 - The Birthday Edition

Posted by Matt on Mon, Apr 20 2009

News

Happy Birthday CakePHP

Gwoo marked April 16th as CakePHP's birthday. Taking a stroll through SVN it looks like the first real commit was #13 on April 24th, 2005 by pies, with the message "0.2.7 pure". If you're ever longing for the days when Cake was pure as the fresh driven snow go ahead and start a project with version 0.2.7.

Tickets and Commits

I've been a bit slacking in following the tickets and commits lately. So since I have nothing much to add here, I'll remind everyone if they want to contribute check out the "Test Cases & Open Bugs in Need of Test Cases (Core Code Only)" report. There you can find defects in need of test cases. It's a good way to learn the core code and unit testing if you're not already a master. Plus for each test case you contribute CakePHP pays you 10 Million Theoretical Internet Dollars.

In The Wild

www.bon-voyage.co.uk

@neilcrookes announced www.bon-voyage.co.uk a site that sells "customised North America experiences to primarily UK audience."

www.awhatup.com

This one was mentioned in last weeks comments. The site is www.awhatup.com, an Asian hip hop site. Thanks to this site I've finally found what's been lacking from American Hip Hop - mac and cheese. Everyone does the money, guns, drugs thing, but how is it we've gone this long without including mac and cheese in da mix?

Miss USA

Also from Twitter: The Miss USA site - check out the favicon for proof. I couldn't pick just one joke here, so I'm going to run them all:

  • Finally, there is something to fap to besides CakePHP.org and the Firefox extension site.
  • What's more messed up? That they let you rate the contestants or virtually all of them are currently 2.5 (out of 5) or lower?
  • Better catch phrase: "See the future face of Cinemax late nights - The Miss USA Pageant" or "The Miss USA Pageant - It's like Miss America, but with more Trump!"

Did I mention they allow user comments, which led to these gems:

  • "You sorta look like a man. sorry."
  • "If you work it with catwalk, a top 15 spot is possible." - Great backhanded compliment.
  • "The only problem with photos is no one can see that you are just as beautiful on the inside as you are on the outside." - Obviously this person doesn't look at the same internet photos as I do.
  • "She sounds like Britney Spears when she talks"
  • "Your dreams FINALLY came true!" - Assuming her dream was to be compared to Michael Jackson ("Your ugly and look like michael jackson. Sick."), then yes: Mission Accomplished
  • "Great body! Butterface."
  • "I kinda wanna give her a sandwich."
  • "what question was she asked where she answered 'daddy long legs'?" - I was caught this on TV. The question was "What insect goes best with a glass of Louis Jadot Le Montrachet 2006?" To her credit she didn't even hesitate.
  • "I'm her sister and she definitely has no wrinkles anywhere on her body!" - ummm...pics or it didn't happen?

I could literally go on for pages like this...

In The Blogs

JS and CSS Compression

Miles took the time to figure out how the quasi-built in CakePHP JS and CSS compression works.

Eventful

cakealot put together a cool looking plugin for handing events in your application. This seems like a good way to organize your code and would be useful if you were building an app that had it's own plugin architecture.

Admin Pages

ActionShrimp is back with a tutorial on how to use the pages controller with admin routing. What I like most about their code is the lack of indention. It's like they're tossing a huge FU to the whole tabs vs spaces debate.

In The Groups

The topic of offline documentation came up again. It's been suggested before, that the easiest thing to do is save the one pager.

This was an interesting discussion on the current state of Cake's plugin system and it's limitations.

Code

DaemonTask

I know this is an old one, but it's the first time I've seen it, so deal. Besides, it's not often I can link to a task.

ACL Cache

I like the idea behind this ACL caching component, but I really wish it didn't depend on the name space file caching engine. I understand the reasoning here (partial key support), but would have rather seen it handled in the component, so that any of the engines would work. Also the benchmarks don't really show any difference when the component is used...someone needs a lesson on doctoring results. My class, "Run a shit load of bittorrent downloads for the before benchmark," begins next week and runs through the spring semester. Taking sign ups now.

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.

Posted in CakePHP Digest | 6 Comments

On The Fly Model Chains With CakePHP

Posted by Matt on Fri, Apr 17 2009

This code has been completely re-worked. The latest is at http://github.com/mcurry/lazy_loader/tree/master. This post has more information about it.

Built For Speed

In yesterdays post I talked about how CakePHP builds a model chain of all the related models. The smart readers (which is really all of you guys. you're the best) probably realized that there is a lot of overhead in bulding the chain, especially for apps with lots of interlinked models. Wouldn't it be awesome if Cake only created the pieces of the chain as needed? Or what if some really awesome member of the community took the time to build such functionality and then shared it with everyone. You know, something like:

httpc://github.com/mcurry/lazy_loader/raw/5ea7dc8d0dd70ec945b33abaf8f67db940ee9764/app_model.php

What The Hell Is Going On Here?

Actually not that much. First we need to catch the constructor and remove all the associations. Wait. What? You crazy! Why would you do that? By removing all the associations before the parent constructor is called Cake thinks there are no related models and won't waste a bunch of time building the chain, when chances are you'll never use half of them. Don't worry, all the associations are first backed up in the __definedAssociations attribute.

What's the deal with the __loadAssociations attribute?

Some of the Cake core models don't play so well with this trick, so this attribute lists models that should have their chains loaded the old fashion way.

Great, So Now I Have A Model With No Chain. Thanks, Moron.

But wait. There's more. See the __get and __isset methods? Those are part of PHP5's overloading ability (Did I mention this was PHP 5.1 or better?). Whenever your code tries to reference a model in the chain that doesn't exist the __get method gets called, which in turn calls __connect to check if it's a valid association. If it is Cake's bind method is called and the model is added to the chain.

Your Code Sucks. It Doesn't Work With $recursive Set

Actually I didn't even check this. I just assumed it won't work. Really there isn't much reason to use $recursive in Cake 1.2. You know the saying: Once you go Containable you never go back. Did I mention this code works awesomely with Containable?

I Tried Your Code And It Broke My Shit

Yea, I expect that to happen. There are probably some incompatibilities with this. I think there is an issue with ACL and probably with other behaviors. It would be cool if you all could try it out and report back.

How Much Faster Is This?

Ahhh, no we get to The Question. Here we go:

Basic controller, no models:

Time per request - 145.636 ms
Calls to ClassRegistry::init - 0

Basic controller, one model, no chain:

Time per request - 142.817 ms
Calls to ClassRegistry::init - 1

Basic controller, one model, nine chained models:

Time per request - 244.533 ms
Calls to ClassRegistry::init - 19

Basic controller, one model, nine dislinked chained models:

Time per request - 162.905 ms
Calls to ClassRegistry::init - 1

Going from one unchained model to one model with a long chain added about 100ms (71% increase). Adding this code brought the number back pretty close to what it was before with just the one unchained model.

How Do I Use It

Pretty simple. Just drop this code into your /app/app_model.php.

One More Thing

I'm slipping this in at the end, because I figure anyone whose stuck around this long would be interested. I'm looking for CakePHP people, who like to read, and want to help me with a project. The bold text should give a pretty good hint as to what the project is. Send me an email at matt -at- pseudocoder.com if you're interested.

Posted in CakePHP | 22 Comments

One More Tip For Speeding Up CakePHP Apps

Posted by Matt on Thu, Apr 16 2009

I somehow completely failed to mention the whole $uses/ClassRegistry/loadModel/chained models thing in my 8 Ways to Speed Up CakePHP Apps post. That's like doing a post on the top 5 adult film stars who hit rock bottom, had it video taped and posted on YouTube, and failing to mention the epic Chasey Lain video (part 2). If you think that link is even remotely SFW, go re-read the description again.

Don't Use $uses Unless You Really, Absolutely Have To

$uses is a controller attribute that allows you to access additional models to the default one. Say you have a blog application and one of the controllers is posts. By default you have access to the Post model. If you wanted to also have access to the Comment model you could do (but shouldn't):

<?php
class PostsController extends AppController {
  var $name = 'Posts';
  var $uses = array('Post', 'Comment');
}
?>

Model Chains

Since Comment is associated to Post through a HasMany relationship you can access the Comment model through Post. Like this:

$comments = $this->Post->Comment->findAllByPostId($id);

The relation chain extends infinitely, including all models down the line.

Controller::loadModel and ClassRegistry::init

Great, but sometimes you do legitimately need access to a model that isn't anywhere in the relation chain. If you are going to use the model throughout the controller go ahead and include it in $uses, but if you only need it in one action there are better ways. They are Controller::loadModel() and ClassRegistry::init().

//the loadModel way
$this->loadModel('Comment');
$comments = $this->Comment->findAllByPostId($id);

//the ClassRegistry way
$Comment = ClassRegistry::init('Comment');
$comments = $Comment->findAllByPostId($id);

Controller::loadModel, not to be mistaken for the deprecated loadModel function, creates an instance of the model and assigns it to the controller. You can then access it the same way as you would as if it was loaded through $uses. ClassRegistry returns an instance of the model. Gwoo prefers the loadModel approach over ClassRegistry. Good enough for me.

Approximate Increase

The dreaded: "it depends." Having one or two extra models in your controller's $uses probably isn't going to kill your app. I added one extra model to my test app and there was about a 4% increase in how long the page took. Then I added seven extra models and there was approximately a 40% increase. So roughly 4-6% for every additional model.

Posted in CakePHP | 8 Comments

Review: Refactoring Legacy Applications Using CakePHP

Posted by Matt on Wed, Apr 08 2009

The Setup

Shortly after Chris Hartjes released his new book Refactoring Legacy Applications Using CakePHP he contacted me and asked if I'd be willing to review it. I jumped at the chance and Chris emailed me the DRM free PDF. After posting it to The PirateBay, I settled in and gave it a read.

The Details

The book is 61 pages and costs $10 for the PDF or slightly less than $20 for the print version. This isn't a book for CakePHP beginners. The ideal reader has good working knowledge of PHP and a basic understanding of CakePHP. Chris gives a quick overview of associations, behaviors, and routing, but it's more of a refresher then a in depth lesson. If you're reading and hit a concept you don't understand take a break from the book and visit The Cookbook.

The Review

In the last CakePHP digest I gave a mini review where I said:

I think by calling it "Refactoring Legacy Applications Using CakePHP" Chris limits his audience, as the book is really about adapting "spaghetti" style PHP code to CakePHP.

What I mean is don't get hung up on "oh, I don't have an application I want to refactor, so this book probably isn't for me." Really the book is about refactoring your brain (which could be considered a legacy application) away from a mish-mosh coding style to CakePHP's MVC system. Think of it like one of those makeover specials they do on Oprah (uh...the ones I've heard about from other people). You don't have to actually be planning to give yourself a makeover to enjoy the show and learn something.

The Before Code

Chris uses a baseball game admin tool for the code that he is refactoring. The before code is pretty much what you'd expect - an orgy of PHP, HTML and SQL all intertwined in a giant sticky mess. Some of the example blocks are pretty long, spanning several pages. It's up to you how much time you want to devote to understanding the old code. Chris does a good job of describing what the code does, but you'd probably get more value by taking the time to carefully read and try to understand what's going in.

The After Code

Each of the sections generally follows the same pattern. Some cracked out PHP code is shown, then Chris explains how to break it up to fit into CakePHP. You'd think that would get redundant, but each section tosses in new elements, building on what you've already learned. There is an emphasis on the fat model/skinny controller approach that all the popular kids are using. If you're not already on the FMSC bandwagon now is the time. In like 6 months everyone will be all SMFC and you'll still be blogging about FMSC and we'll all make fun of you.

I really like this style of learning over the "tutorial" approach seen in other CakePHP books. By looking at the legacy PHP code and seeing how Chris turns it into CakePHP your not just following some cookie cutter blog tutorial. You're forced to think about what's happening and can apply that reasoning to your own code. You do more learning and less memorizing.

The Part Where I Say Negative Things and Wax Nostalgically

The refactoring in the book went smoothly...a little too smoothly. I would have liked to see more crazy, dailyWTF style shit. For instance Chris admits that the database is shared with another CakePHP app, so it already follows Cake's conventions pretty closely. Cake has a reputation for being too rigid, but really you can make the models fit any database structure. I would have liked to seen a section on either porting data or adapting models to fit odd database schemas.

When I was rebuilding XplodSony.com (with Cake 1.1 no less) it was going to share the product database with SonyMETC.com. SonyMETC is written in WebObjects, which is a framework for those who like to program on a keyboard made of broken class, covered with tetanus. Needless to say, that database fit the Cake conventions about as well as The Glove fit OJ, but thanks to some model craziness it was still still able to work. I know both of these sites kind of look like shit now, but don't blame me. I broke up with them two years ago and they've been on a downward spiral ever since. I have that affect.

The other section I would have liked to see is something on partially refactoring an app. Sometimes it's just not possible to rebuild the whole thing at once, so you want the legacy app and the Cake app to run side-by-side. We're doing this at my current job. Most of our app is a V2 of an old PHP app that is now running on Cake. However we knew that there was no way we'd have time to build the reporting system before launch, so we took the legacy reporting system and wedged it into the Cake app. This allowed us to launch on schedule and take our time building the new reporting system right. And damn straight we took our time. A year later and we're almost half way done!

The End

So is the book worth your $10? Really $10 isn't that much, especially for what you're getting. I know the economy sucks right now and you're probably trying to be smart about your money. Here's the way I see it. In a year either the economy will be recovering/ed and everyone will be hiring CakePHP devs at which point that $10 will look like nothing next to the $250/hr we Cake devs pull down. OR society will have collapsed into a post-apocalyptic lawless cluster frak (with zombies) and money won't have any meaning. Either way you win, right?

PS

Obviously, the Pirate Bay thing was a joke. I would never do that. Chris worked very hard on this project and it shows. Don't copy that floppy!

Posted in CakePHP | 3 Comments

CakePHP Digest #11 - Food Metaphors

Posted by Matt on Mon, Apr 06 2009

News

New Book

Chris Hartjes released his book, Refactoring Legacy Applications Using CakePHP. The first review of it popped upwithin 24 hours. I've read it and will be posting my review sometime this week. My biggest critique (which could also be construed as a compliment) is with the name. I think by calling it "Refactoring Legacy Applications Using CakePHP" Chris limits his audience, as the book is really about adapting "spaghetti" style PHP code to CakePHP. You don't actually have to be refactoring anything for the book to have value. He could have even gone with a foody title like "From Spaghetti to Cake - Hmmm Hmmm Good" or "You Spaghetti Sucks - Eat My Cake."

CakeFest Again

This piece of news got mentioned in the last digest (where I did a poor job of detailing it), but there is now an official Bakery announcement: CakeFest III in Germany. Buried in the article is the announcement of cakephp.de, the German translation of cakephp.org. The article also teases that "there are expected to be some very exciting announcements about the future of the CakePHP project."

CakePHP 1.3 Wiki

I hadn't seen this before, but there's some interesting stuff in the CakePHP wiki on The Chaw about the direction of version 1.3. First is a hit list of potential changes for 1.3. As items are finished information gets added to the 1.3 migration guide. Also, for the larger changes there is an RFC section which goes into greater detail.

Confusion in 3, 2, 1...

The Cookbook flipped the navigation to the left side sending twitters everywhere into daze (1, 2, 3, 4).

In The Blogs

Tutorials

Lots of new tutorials this week. The first is a series of posts be ibernat over at smashingmagazine.com's forum.

The colorfully named actionshrimp.com posted two parts of 72 part tutorial (I just made up the 72 thing, although now that it's out there they should feel obligated to complete it or I will feel let down). Check out part 1 and part 2.

ACL Tutorials

I'll be honest, I didn't read either of these. I have the attention span of a three year old these days. The posts are Getting Started with ACL in CakePHP and CakePHP ACL Tutorial - What and How. I'm not sure if either of the tutorials mention this, but what really helped me understand Cake's ACL was going right to the database. After every grant or deny command I would check the aros, acos and aros_acos tables to see the changes.

"Dynamic" Javascript

I'm sparked by this post from Teknoid, but he's certainly not the only one who pushes this concept. Also I'll mention teknoid's blog is awesome and I just happen to disagree with this one post. In fact I still wake up reaching for my shotgun (conveniently nearby in The Backup) after nightmares that this "bug" isn't a bug.

What is the obsession with putting PHP in JS files? Leave your functions static inside the JS files and set the variables they act on in your views/layouts with PHP.

<script type="text/javascript">
alertMe("<?= $session->read('User.username'); ?>");
function alertMe(msg) {
  alert(msg);
}
</script>

Ok, no one would ever do that, but imagine that username is actually a data array (which can conveniently be converted to JS with $javascript->object()) and the alert function is actually a function that makes ajax requests to your cloud servers and returns rounded corners. Whatever, you get the point. Your JavaScript files can be crushed and served super fast by your webserver (or CDN) which doesn't need to invoke PHP and you still have the flexibility for dynamic craziness.

The Rest

There really were a lot of good posts these last two weeks. You've probably all seen these since @cakephp has been sending out the same links (although @cakephp's twit rate is declining after only two weeks - unless you count the tweets that are mistakenly posted on @cakephp instead of the devs personal accounts. *zing*).

CakePHP desktop wallpapers. Someone should do A/B testing to find out what type of desktop wallpapers hurts your chances with the ladies more: half naked super model or CakePHP themed.

Displaying custom error message with the right HTTP response code

Paginate associated model’s data in CakePHP

In The Wild

recipestar.com

Matthew Inman, who created the (formally) CakePHP based dating site mingle2, launched his latest project: recipestar.com. It's almost as if Matt's sites are following the progression of his life. First he was looking for that someone special, but now he's found her/him and settled into that daily routine where you have to deal with the "what the f is for dinner" question ever night. Look for futures sites (in this order) on weddings, parenting and relaxation techniques when you feel like launching a three state killing spree.

soonerquotes.com

@ruebenramirez announced soonerquotes.com. If I gave you a million guesses as to what the site does the first one would be: "Quotes from people related to the University of Oklahoma sports teams," which would be wrong. The next 999,999 guesses would be: "Really? Are you sure?"

hotscripts.com

@aaronforgue re-launched the venerable hotscripts.com. Remember when it was 1999 and you first discovered this site and thought it was the greatest thing since you realized you could set the from address of emails to anything and spent days pranking your friends? Man, we were so naive then.

gamesync.com

Miles J, who you probably know as one of the more active contributors to the Google Group, announced his new site GameSync.com.

Tickets and Commits

There were a bunch of requests for new callbacks including beforeSaveAll, beforeDispatch and afterStartup. The best part of all these was Nate's comment:

It may have escaped your notice, but we currently have over 320 open "suggestions". If didn't reject any them, this framework would quickly devolve into a pile of Zend. Oops, did I say "Zend"? I meant to say "incohesive class libraries of varying quality".

Code

beanstalkd

David Persson released a plugin for the Beanstalk Queue Service, which I'd never heard of before, but seems really cool and dead simple to use. I would love to use this where I work, unfortunately the product management team prefers to just let the browser hang, with no other indicators except for the normal mouse hourglass pointer, while extensive background tasks are performed. I guess you could make an argument for either approach.

Wildflower CMS

Version 1.3 of the Wildflower CMS was released. This may be a great piece of software but the name makes me suspicious. How did the author miss such a clear opportunity to call it Wildflour CMS and be part of the cheesy baking tie-ins trend.

In The Groups

Who Has The Answers?

There was actually a fairly civil and well thought out discussion of the CakePHP resources and areas it is still lacking. I almost posted something like "The problem with CakePHP is the framework is like an 80 year old - slow and full of bloat, but the docs are like a newborn - undeveloped and constantly pooping itself" just to set the world right again.

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.

Posted in CakePHP Digest | 10 Comments
4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12

Categories

  • CakePHP
  • CakePHP Digest
  • Interviews
  • Screencast

Popular Posts

  • Why HTML5 Video Won't Replace Flash
  • CakePHP Digest #24 - Drama Free
  • How A Small Change To The Buy Now Button Increased Sales One Gazillion Percent
  • CakePHP Progress Bar Shell Task
  • Interview with Joel Moss creator of Codaset

My Sites

  • PlanbookEdu.com
  • RSStalker.com
  • Later.RSStalker.com

My CakePHP Plugins

  • Asset (JS/CSS) Packager
  • Custom Find Types
  • Html Cache
  • JavaScript Validation
  • Site Status Page
  • Static User
Copyright © 2010 PseudoCoder.com, All Rights Reserved.
Powered by Croogo, Built with CakePHP