Free CakePHP E-Book - Super Awesome Advanced CakePHP Tips

Posted by Matt on Wed, May 13 2009

For those of you who just want the book

This is the download link ---> Super Awesome Advanced CakePHP Tips
Updated to V1.1, fixing a few small things.

For those that want a 1500 word blog post

I've been sitting on this thing for the last two weeks and figure it's about time I just let it out. Ahhhh....so much better. Now, about the book. What better way to introduce it then a fake interview? Off we go!

What exactly is this thing and why should I waste my precious bowl time reading it?
At the moment there is no lack of CakePHP books geared towards beginners. But, there really isn't much for anyone who has mastered the basics and wants to do more. This e-book is for you guys and gal (I'm sure there's at least one out there somewhere).

I suck at CakePHP. What's the best way to learn the basics so I can get up to speed and read your book?
Check out Chapter 2: "How to Learn CakePHP". It details two paths for learning the framework - a free one and a pay one. I'm interested in feedback here, since it's hard for me to remember what it's like learn the framework. I just remember being really frustrated at times and blacking out, only to awaken covered in blood and standing over a dead hobo. Not good times.

How much is this thing going to cost me?
Nothing. It's free.

No really.
Seriously. Free. You know how when you're watching an independent movie or playing an indy video game you cut it some extra slack and overlook a few minor flaws? Do that there too. Thanks.

When did you start working on this?
The original idea was hatched in December 2007. At the time I was planning on writing a series of Advanved CakePHP posts. After I had 12-15 or so I was going to roll them into an e-book. Naturally I fizzled out after 2 posts.

Fast Forward to Oct 08 and I'm sent a copy of CakePHP Application Development to review. I realized as I was reading it (and confirmed by one of the comments on that post) that there was a lack of upper level Cake books/documentation. I also realized that in the year since I'd given up on the advanced series I had a bunch of decent posts that, once I cleaned out all the cursing and porn references, would make a decent e-book.

It's kind of dick of you to spend all this time creating an e-book, but then hardly contribute to the Cookbook. Do you feel any remorse or are you so hell bent on personal glory that it has crushed all rational thought in your oddly shaped head?
I struggled with this - I really did. In my defense I would say most of the content of the book isn't really appropriate for the Cookbook. That still doesn't excuse why I haven't contributed more. Although the Cookbook is great there are gaps (though they're becoming harder to find). I don't know...maybe it's because I spend more time in the API or maybe I'm still bitter that tempdocs, which served me so well, was whacked without even given a chance to make a tearful deathbed speech.

What IDE did you use to create the book?
I actually went through two before settling on Open Office. I started with Google Docs, because I figured it would be cool to be able to write whenever/wherever I got inspired. By about 30 pages Google Docs started to really choke, plus the PDF generation was mediocre at best.

I moved the whole thing to Word and spent like a week re-doing all the styles. But Word just gave me other problems. Whole pages would disappear until I scrolled around a bit and then they'd randomly re-appear. Plus I tried a bunch of different PDF printers and they all sucked.

Finally, I moved to Open Office and wasted another week fixing the styles again. This time everything worked pretty well and the built in PDF generator actually did a decent job.

Is this what you've been busy with and why you haven't blogged as much and when you do blog the posts blow?
Yea, pretty much. I'm also obsessed with converting all my open source Cake code into plugins. I'm all over plugins like a meathead frat dude trying to impress his buddies as a way to cope with his feelings of inadequacy when he sees a slightly unattractive chick with self esteem issues whose had too much to drink.

What's with the Mark Story sections?
This one is going to take a bit. Way back in the pre-RC days of 1.2 if you used the console to bake model tests the resulting test cases would have to extend the model and set the database to use the test_suite. This approached sucked and there was a better way. If you used the ClassRegistry to get an instance of the model it would set the database automatically. When I was putting the book together I knew I wanted to include a section of fixing the model unit test.

I also had an inkling I wanted to do a proper view unit test section. It would have been a gaping goatse-esq hole if I had a section of M(odels) and V(iews) and not C(ontrollers). Before I could get my shit together and write it Mark's article came out. Fuck. It was good and I really hated the thought of re-writing the same thing.

So, I got the brilliant idea to get others to contribute sections. I emailed Mark and a bunch of other Cake devs to see if they were interested. Predictably, everyone was too busy raking in that phat CakePHP bank to contribute. Except for Mark who not only agreed to let me use that piece, but also his forthcoming (at the time), landmark, life altering, spiritually awakening piece on mock objects. *genuflect*

Why not charge $$$ for this thing?
Another long answer. Continuing the above section...sometime later I realized that Cake had actually fixed the core to generate better tests and my Model section was pretty much shot. But at this point I already had Mark on board, so to sell this thing I would either have to a)cut his part and lose like 1/3 of the book or b) negotiate some sort of split.

Realistically I knew this thing wasn't going to make a ton of loot. Certainly not enough add another wing to the PseudoCoder estate. Take a look at this post from John Resig. It's a little unclear how much he's made on that book, since he never reveals how much he received up front $7500. What is clear is that he isn't killing it. I mean, if the fricking creator of jQuery can't make a fuck ton of cash on a JavaScript book...really, what chance do the rest of us have? It's John Fucking Resign, writing about JavaFuckingScript! Shouldn't this be the #1 best seller of all time, crushing The Bible like an empty Miller High Life against it's forehead?

This book is so full of typos, grammar mistakes and bad code. Where should I send my bitchy emails?
Take your pick - all of these people took the time to proof read it and gave me immensely helpful feedback.
Paddy Foran (blog) - Paddy sent me about 100 pages of speling, grammer and typeos, which is amazing since the book is only 64 pages. I dare you to find a mistake that he missed and then harass him endlessly about it. I DARE YOU.

Shawn Poulson (blog, friendfeed, twitter) - Shawn helped fix my atrocious PERL regular expression skills as well as suggesting using the Heredoc syntax when including JavaScript in views.

Jonathan Langevin (site, cakephp forum) - Jonathan sent me a bunch of spelling errors, which I probably could have figured out on my own if I those damn squiggly red lines under the words weren't distracting me so much.

Heath and Sohaib - both challenged me on the "Getting the Logged In User from Anywhere" section.

Felix Geisendörfer (site) - Felix is a superstar and provided some great pointers.

I'm sure I'm missing someone. If you're that someone, know that as angry as you are for not being mentioned, I feel 1/8 as bad for missing you.

What as the most significant thing you learned while writing this?
I feel like a moron for not knowing this. Apparently the correct slang is friggin'. But for years I've been using "friggen" - which has a completely different meaning. It's no wonder that my friends would act strange when I'd ask "anyone want to hang at my place and play video games and other friggen stuff?" Then they'd show up five minutes later and always seem disappointed at 3AM when I said I was going to bed...like they were expecting more...

This brings up an important issue. Has there ever been cursing in a programming book before?
Not that I've ever seen, but I'd be interested in hearing about it. My goal is to have the first NSFW programming book. Set your dreams high, kids.

I have question/comment about the book. How should I contact you?
Send me an email. Hit me up on twitter. Leave a comment on this post.

What's next?
Not much for the book. I'll probably fix it up and add new sections from time to time. I've already received a few good suggestions. I have a couple good blog posts ready, including "How To Program While Shitfaced Drunk" and "Stop Fucking With Your JavaScript". They just need a few more drunken tangents and they'll be ready to go. Keep an eye out next week.

Posted in CakePHP

44 Comments

Paddy Foran said on May 13, 2009
I can't believe you cited UrbanDictionary.
Matt said on May 14, 2009
I view UrbanDictionary as a creditable authority.
Mark Story said on May 13, 2009
Hey Matt, nice to see if finally released and free of its earthly bonds. Nice work :)
nate said on May 13, 2009
Matt, this might possibly be the best CakePHP book ever, which between you and me is saying something... bad.

Kidding, kidding. This is a really comprehensive collection of tutorials, and we'll make sure it gets distributed far and wide.
Matt said on May 14, 2009
The lowest mountains are the easiest ones to climb. :)
Chris Hartjes said on May 14, 2009
So Nate, does that mean you were lying to me about my own book being good? ;)

Great resource Matt!
Walter said on May 14, 2009
Thank you so much. I think that's all I need to say. Oh wait there's something else - thank you very very much. :D
Daniel said on May 14, 2009
Hey Matt, thank you very much!! A few new tricks I've learned this early morning ;)
Robert Navarro said on May 14, 2009
Haha that was a highly entertaining post! A great break from programming and well worth my time! Now the fun part.....NSFW + Programming Book.....that's totally epic win...
Nikolay said on May 14, 2009
Hi!
Well done, thanks for the book!
Some of this tips i've found already by myself, although i've some questions and ideas for improvement.
As on the page 39, i'm using similar merge function to init some settings. My approach is to declare all possible params and merge it with incoming array:

$settings = array('def_param_1'=>false, 'def_param_2'=>false, 'def_param_3'=>false );
$get_params = $this->params['named'];// url/controller/action/def_param_2:123/hacked_param:zzz
$settings = array_merge( $settings, array_intersect_key($get_params,$settings) );

$settings //def_param_1=false, def_param_2=123, def_param_3 = false

I found it very useful if using many named parameters in the view.

As on the page 38, i'm trying to combine add/edit action in one.
I'm developing multi-user app, so i need to check if the entry that user trying to edit really belongs to him, if he saves new entry then save his user_id too:

function admin_edit($id = null){
$user_id = $this->Session->read('User.id');
$data = $this->Model->findByIdAndClientId($id, $user_id);

if(empty($this->data)) {
$this->data = $data;//just show
} else {
$this->data['Model']['user_id'] = $user_id;
if($data) {//update
$this->data['Model']['id'] = $id;
} else {//create
$this->data['Model']['id'] = '';
}
if($this->Model->save($this->data){
//Ok
}
}
}

There is no overhead becouse of findBy-statement if user will to add new entry since findBy will just return false/null if first '$id' param in null.
Matt said on May 15, 2009
Part 2 first - the add/edit thing. I intentionally left the security stuff out. It'll be different for everyone. And the setting the user id stuff I think is better done in the model callbacks. There is a section in the book about this.
Matt said on May 15, 2009
The first part of your comment - Either way is cool. I've noticed it both ways in the Cake core. Agree that as the array of default options gets longer it's probably better to set it to it's own var.
Joel Moss said on May 14, 2009
Matt, you're a funny guy. Keep the good work coming dude, and let me know if you need a hand.
Dan said on May 14, 2009
Made me smile on a dreary thursday morning, thanks!

I might just ditch my static userData property on AppModel :D
Nathanael Kane said on May 14, 2009
Excellent read, definately picked up some great tips.
Orgasmo Spermlicker said on May 14, 2009
This book is good. But the framework is bullshit. The book is good proof for this! you have to make special this and special that to get it working ok. also auth is totally primitive ACL but the way to implement it is complicated and cumbersome and will produce errors, like the cake devs did it with errors themselves. all over cake musst get much, much better. but I would recommend not spending time with cake as their are much better solutions. cake people a living in a black box on the dark side of the moon, they do not see what is happaning in the world. cake is a way to social exstinction, to total loss of time and total financial banlruptcy! do not use it if you still want to be on the block in 2010! cake is a fake project injected by other frameworks to make developers loose a lot of their living time and to fall behind modern development of frameworks in the wild. cake is made to blind you, to make you weak, to make you impotent and to finally make you cry in your own vomit about all the bullshit that happened in your stupid life since you started to use cake. the cia is using cake to make people spent millioln of hours before their screens doing stupid repetetive tasks so you can not use your power to understand the world. it is an army mind destruction and psyop tool that will kill your existance and make you a rat-eating underdog. cake will make you believe in god and do lots of stupid things, bit you will never ever be happy again in your life, so BEWARE! the book is a good warning - a good framework does not need books like this.
Brendon Kozlowski said on May 14, 2009
I got an email in my inbox this morning similar to this message. I think it was about just receiving money that was locked in an account, and to receive the rest of the money, I needed to send $500 for which the person would then send me $10,000 which was only a %5 amount from their total amount.

GOOD DEAL, I'M IN! I WILL ALSO BEWARE OF THE CAKE. THE CAKE IS EVIL. I SHALL BOW BEFORE ORGASMO SPERMLICKER!

At least it continued the hilarity of the initial topic. :P Thanks for the tips, Matt!
Matt said on May 15, 2009
"the book is a good warning - a good framework does not need books like this."

Actually this is why I picked Cake. I check out CI, Zend and Syfony, but realized these frameworks weren't conducive to neglecting my family and personal obligations to produce a book with no financial reward. CakePHP FTW!
Jon Adams said on May 14, 2009
@Orgasmo Spermlicker: you're doing it wrong.

Matt, thanks so much for doing and sharing this.
elvy said on May 14, 2009
great work in your usual fun style of writing - thanks!
ADmad said on May 14, 2009
Good stuff Matt. Though i think you could have squeezed in one more adjective into the book title :D
Bisi2poche said on May 15, 2009
Hye Matt,
thanks a lot for this nice book.
I hope it will grow.

I noticed a little typo in the second code of page 39; missing a end bracket for Array :

'detail' => true),
$options);
Matt said on May 15, 2009
Thanks. Fixed.
WyriHaximus said on May 15, 2009
Hey Matt,

On page 53 on the last line you write "ypu" rather then "you" :P. Great book btw :D!
Matt said on May 15, 2009
Thanks. If someone would invent to use computers to spell check a digital document they'd be rich.
Kym said on May 15, 2009
Hey, go to hell, I felt stupid reading your book!

Nheee, thanks anyways, its a really good "book", its my fault felling stupid.

Please keep the good work :)
Brendon Kozlowski said on May 15, 2009
So Matt, do you really want someone to read through it all and send you back corrections? I can start over with my reading and make notes when I come across something.
Matt said on May 15, 2009
Definitely send corrections as you find them. I've already posted an update that fixed a few things.
Brendon Kozlowski said on May 19, 2009
Okay, I've sent along an attached (zip) RTF of mostly grammatical errata.
Guillaume said on May 16, 2009
Hello,
Thanks for this great work.
I tried to implement my own find type your way. I found some typos (two underscores instead of one in the name of the function) but it works perfectly.
I just find a case where it doesn't.
I use my own News::find('latest') in my AppController::beforeFilter() callback to fetch the latest news and display them on all pages.
When I want to display a page from a plugin (and not from my application) : it doesn't work. It seems that instead of looking up the _findLatest method in NewsModel, it tries to find it in my [Plugin]AppModel. As it doesn't find it, there's a fatal error. Strange isn't it?
Matt said on May 17, 2009
The underscore thing is fixed in the latest update. Also the GitHub version should be fine.

I haven't tried this with plugins yet, but if you plugin AppModel extends the app AppModel, then I would expect it to work fine.
Guillaume said on May 16, 2009
It works better if I use ClassRegistry::init rather than loadModel.
Matt said on May 17, 2009
That's weird...loadModel actually calls ClassRegistry::init.
Gordon Pettey said on May 19, 2009
Page 20:
var $belongsTo = array('CreatedUser' => array('className' => 'User',
'foreignKey' => 'created_user_id'),
'ModifiedUser' => array('className' => 'User',
'foreignKey' => 'modified_user_id'));

Since Cake will use those FK by default, is it really necessary to set them?
Matt said on May 21, 2009
You're right, of course. Thanks - it'll be fixed in the next release.
Dan said on May 30, 2009
This book is awesome Matt. I've found myself opening it up many times during development to use a technique you mentioned or just to see what in my apps I can improve/optimize. Thanks again for putting this together.
Zoltan H said on Jun 01, 2009
Great book - this is best thing I've seen all week :)
primeminister said on Jun 05, 2009
Indeed nice book! As I said before it is a great source for ticks and tips. I already used some of it in my new application.
Thnx Matt!
Hugo Leite said on Jun 05, 2009
I will surely keep this one by my side when at work.

John Resig received $7,500 as an advance, just thought you guys would be interested, not much. How do I know? It's actually in his post, top right text of the letter "Advance = $7,500.00"
Matt said on Jun 05, 2009
You're right of course...don't know how I missed that. Thanks for pointing it out.
JoHo said on Mar 18, 2010
Nice work! I added a short blogpost about it.
Josh said on Sep 29, 2010
Looks very interesting! But I wonder how much of the informations apply to the current versions of CakePHP (1.2.8 and 1.3.4)...

I'm still quite new to CakePHP so I will take this as some sort of source for "what was CakePHP able to do a few months ago?", but it would be very useful to have updated informations about deprecated or improved stuff (not that I learn things that are really outdated already).

But very nice work anyway, thanks (should have found this a few weeks ago already)! :-)
Lukas said on Apr 04, 2011
Link to the book is broken. Please fix it. :)
Matt said on Apr 04, 2011
Fixed. Sorry about that.