12-step program to get addicted to CakePHP

Yep, this one works in reverse of the other “popular, so-many-steps” programs.

Step 1. – Unlearn your old habits

Whether or not you have great habits, familiarity with many other frameworks, or no experience at all… it will still be of great benefit to open your mind and just try and learn the cake-way. You might disagree, you might dislike, but if you want to harness the power of CakePHP, drop your prior knowledge for just a second and try to understand why things are done the way they have been. After that, you might agree or like or even start getting a little addicted to the new paradigms and new opportunities that will become available to you as a developer.

“It’s a lot easier to create a masterpiece on a blank canvas, than it is to paint over someone else’s mess.”

Step 2. – Help out with the docs

Time and time again I’ve heard that CakePHP documentation “sucks”. Personally, I think it couldn’t be further from the truth (but let’s stay on topic). The new manual (AKA “The Book” or “Cookbook” http://book.cakephp.org) has become better than ever. Most importantly, it is a community-driven effort. Any part of the book can be edited and you are very welcome to improve the documentation in any way. Whether fixing a spelling mistake, providing a code sample or clarifying something in the explanation, everything counts and everything is important to your ultimate addiction to the framework. In other words, if you find something lacking you have the power to make it better.

Step 3. – Join the mailing list (google group)

CakePHP has a pretty large, active and helpful community: http://groups.google.com/group/cake-php. Join it, post any questions if you get stuck or try to give advice to someone else. By participating, you are not only helping out others (which is a good feeling, if nothing else), but also get to learn a little from reading and possibly solving other people’s dilemmas.

Step 4. – Jump onto the friendly IRC channel

To top things off CakePHP has a great, active IRC channel, which is excellent if you need some real-time support. Not only is the channel friendly and helpful, but it can also be quite entertaining at times and certainly can be used as a great learning tool to further increase your addiction.

Step 5. – Start coding, already

All the reading and preparation should not be discouraged, but the most important part is to just sit down and start coding. Even if you simply follow the blog tutorial. Even, if you are not sure if the approach you are taking is the best one. Code is constantly evolving and refactoring is just a natural part of a developer’s life. The sooner you get started the sooner you’ll be addicted. Of course it goes without saying, that nothing good will come out of your baking, unless you really get your hands in the dough.

Step 6. – Become best friends with the API

At the time of this writing CakePHP has acquired a brand-new API (only a few days old), thanks to Mark Story and other contributors. Yes, there are a few glitches still, but it is an indispensable tool for any developer. It might be a little overwhelming at first, but you really need to take it easy and learn to love it. The API is the ultimate answer to many of your cake-baking questions. Though the road to understanding might be a little rocky at first, the eventual habit will be hard to kick.

Step 7. – Fall in love with test cases

Is there anything better than the CakePHP API for a developer?
Indeed, there are test cases. The core test cases (which is what I’m referring to), cover about ~90% of the framework code. They show you every little detail about how to use this or that method in CakePHP and after a rough time with Step 6, will give you a great boost in moving up the scale of addictiveness.

Step 8. – Submit an article to the Bakery

So now you’re almost there… you’ve probably hit a rough bottom once or twice, but got back out on top. This would be a prefect time to share your experience with the community.
Have you built in an awesome app that needs to be seen by the world? … share a case study.
Got a sweet, little helper that we could all benefit from? … write about it in an article.
Figured out a function to make your life just a little easier? … submit a code snippet.
The bakery is the ultimate hub for sharing your knowledge with others and learning a thing or two in the process while getting exposure… and further twisting your already addicted mind.

Step 9. – Follow the time-line

At this point you must have the latest and the greatest. Following CakePHP time-line is educational… and important, if you wish to stay on top of the world. http://code.cakephp.org/timeline gives you a perfect overview of what is happening on daily basis in the sad life of cake bakers. You’ll notice that there are almost daily code commits to the core, countless tickets being answered and closed due to a variety of “fun” reasons. But, more importantly, you see that this thing is alive and kicking.
It’s comforting to know that when you’ve gone through all the tough and rough steps, so far, you are not alone out there. Cake devs are working hard and tireless to ease your pains.

Step 10. – Write a test case and submit a patch

Can I imagine that you are a true cake-addict by now? Well, say what you wish, but nothing is perfect. If you see something you dislike or have a brilliant idea to optimize something in the core, then be a friend and submit a ticket with a patch and a test case. But, please, be sure to do it right! … “This thing is not working!” is not a helpful ticket to anyone.
Take your time, sit back, and think about how to get the patch and test case working so that your next great idea will be quickly addressed and implemented. After all, nobody likes to wait for the next dose of addiction.

Step 11. – Contribute

It doesn’t matter if you are a cake guru, an OOP master, or a PHP evangelist. Contribution to the project can come in many ways, shapes and forms. As mentioned before…. a little help with the docs, with related projects, with a clever Model Behavior, with a nice code snippet (a damn post on a blog, if all else fails)… is still a useful contribution. Everyone working on this and many related projects is a volunteer. Respect that, and become one as well. It will be a habit that’s hard to kick and in the long run it may actually (and surprisingly) play a very positive role in your own life.

Step 12. – Start dissing other frameworks

Yes, I’m joking around. Regardless of how far you get along in your life as a cakeaholic, it is always important to realize that no single tool is always right for any job. There are many great frameworks out there made by some nice and kind people to enhance your life as a developer. Obviously, I will encourage you to scream: “Cake is the BEST!” at every opportunity, but be respectful to those others, who are less fortunate.

P.S. New! This simple 12-step plan is provided completely free of charge, but you are welcome to send me two easy payments of $9.95 and one complicated payment of $12.35….

What can we learn from CakePHP tests?

Update: Currently the API for test cases searches is down (but coming back soon).
Remember, that you still have the test cases in the core of cake, so you can and should utilize them all the time ;)
(If anyone wishes to volunteer their time to help out to bring test case search online, please contact Gwoo or Mark Story)

First things first, all current CakePHP test cases are now searchable here:
http://api.cakephp.org/tests/

If you ever find yourself stuck wondering how to use some feature in CakePHP look to the test cases to provide a helpful hint.

Let’s consider an example.

I don’t know how to use SQL’s BETWEEN syntax in cake… let’s see if there are any matches for “between” in the test cases.

Search at the above link, and a few results, but here’s one: DboSourceTest::testArrayConditionsParsing
Hmm… conditions parsing? Sounds about right…
And looky-looky what we’ve got there.
All sorts of examples including the BETWEEN syntax.

Hopefully you can see how great it is to have the test cases available and how much you can discover and learn by digging around in the tests source code.

15 Essential CakePHP Tips

1. Save() does not work!
Sometimes it happens that save() fails without any obvious reason. Your data array looks fine and you’ve build the form correctly, etc., etc., but no query was executed. It is very possible that save had failed due to validation errors. Maybe you are updating some model and while the current fields in the form pass the validation, there is a chance that some “other ones” are causing the validation rules to fail. An easy (and helpful) way to see what’s going on with validation is to do pr($this->validationErrors); in your view. By employing this method you’ll see exactly what’s happening with your model’s validation. The other option is to pass false as a second parameter to save(); in order to disable the validation. However, the latter method does not give much of hint and should not be used to fix a failing problem, but rather to purposely avoid validation.

2. Save() still does not work!
Do you have beforeSave(); in your model or app model? Always double-check for this method, and even more importantly, ensure that it returns true.

3. Validating on create or update
CakePHP has an 'on' key to be used in your $validate array. It allows you to specify whether the rule should be enforced during a new record creation or during an update of an existing record. For example, if you only want to check for a unique email address when you are creating a new User account, you’d add 'on' => 'create' to your $validate array. Therefore, this rule will be ignored when you are updating/editing some user.

4. Mind your cache
You’ve made some changes to your tables, but you app “ignores” them… You’ve moved some things around, bur your app doesn’t seem to “notice” that…
Clear the cache. Delete the files from your app/tmp/cache. Be sure to only delete the files and not the directory structure.
Basically if you notice some strange behavior in your app, just keep in mind that it could be caused by the cache.

5. I’m losing the extra URL parameters when paginating
You need to retain some extra URL parameters during pagination. For example the URL is something like /products/view/45. Yet, when you build the pagination the ID (45) is lost… Well, all you need to do is add this line of code to your view: $paginator->options(array('url' => $this->passedArgs));

Update: this is likely fixed in the recent builds of CakePHP, but still good to be aware of.

6. Using afterFind()
Model::afterFind() allows you to perform some data manipulation after the Model’s find method. Here’s a sample usage in the model:

function afterFind($results, $primary=false) {
  if($primary == true) {
	// do stuff to the $results
  }

  return $results;
}

$primary will be set to true after your find() method is executed and some results are returned. After you modify the $results you will return them back to your app (controller).

7. I need to know the basic information about my table
Try this: pr($this->ModelName->schema())

(Thanks, gwoo, for the hint)

8. How do I check for a non-empty field in CakePHP 1.2?
Update: cake core now has a 'notEmpty' rule built-in, so definitely use it instead.

For historic purposes only:
The old VALID_NOT_EMPTY constant is now deprecated and there does not seem to be a rule to replace it… Well, it’s easy enough by using: 'rule' => array('minLength', '1')

Martin Bavio pointed out that having space characters (only) as your field data will make the validation rule pass and this is probably not a desirable effect. Using this simple regex, instead, will catch an empty string with space characters: 'rule' => array('custom', '/\S+/')

9. Avoid using the $uses array
You’ve got two completely unrelated models, but you need info from one in the controller of another. The first idea is to add them to the $uses array. Hey, it’s easy and gets the job done. Well, to make the long story short, it’s bad practice. Think about your model bindings and ensure that models are really not related to one another. Sometimes your User model is definitely not related to CommentRating, but you absolutely need it in your users controller. Well, just by chance it appears that User->Post->Comment->CommentRating. It’s a deep binding that may not be obvious at first, but by employing such a chain of models you can easily avoid using the $uses array, when it’s really not necessary.

Update: if you truly need to load some random (and definitely unrelated) model in your controller, do it like so in the given action:

$MyModel = ClassRegistry::init('MyModel');

or even:

$someData = ClassRegistry::init('MyModel')->find('all', array('conditions'=>array('MyModel.name LIKE'=>'%'.$name.'%'))); (the latter, chaining, example is PHP5 only)

10. Clean-up ugly HTML

It’s no secret that CakePHP often outputs some very ugly and hard to read HTML. This little trick will make it a lot cleaner.
Create a file named app_helper.php in your app’s root directory.

Next add this function to it:


function output($string) {
return parent::output($string . "\n");
}

Take a look at your HTML now… much better.

(Thanks, TommyO, for the hint)

11. How can I access session data in the view?
Very easy. You have the $session helper available.
Just try it: pr($session)
Update: if you have already written some variables to the session, then try pr($session->read());

12. I need to save data from multiple models
Don’t even think about using loops and other trickery. There is a very nice (but not well documented) method saveAll() available. It will let you save data from multiple models at once. Granted, it takes a little time to figure it out, but once you get it working it is really a time saver. Try using it with some dummy data, and make sure that your data array is properly formatted and associations are setup correctly.

13. Static pages and routes
I really don’t like having /pages/ as part of the URL for my static pages. Well, they are static… so let’s make them .html instead (at the same time we sprinkle just a little of security by obscurity mantra).
If you had links pointing to www.example.com/pages/myPage/ they should now point to www.example.com/myPage.html and add this to your routes:

Router::connect('/(.*).html', array('controller' => 'pages', 'action' => 'display'));

Sweet.

14. The fastest way to build a form in CakePHP


echo $form->create();
echo $form->inputs();
echo $form->end();

It is just a step beyond scaffolding, but really this is how easy it is to build a form in CakePHP. Just give it a go.

15. Get to know CakePHP by using Bug tracker
Update: recently CakePHP has switched to another system from Trac.

CakePHP is constantly evolving and if you are serious about developing on top of this framework it is very important to keep up with the latest and greatest and to get familiar with some of the new and upcoming features. code.cakephp.org is a great place for this:

a. You can download nightly builds from here.
b. Keep an eye on the Wiki to see current status of CakePHP project and helpful hints.
c. Use Timeline to see the latest code updates. Pick “commits” to filter the updates.
d. Take a look at the code of test files to see how a certain feature should be used
e. Submit bugs and requests for enhancements, but read this first: http://book.cakephp.org/view/759/Bugreport