Posterous theme by Cory Watilo

Getting started with testing in CakePHP

I've started working on a new project called Hlasite.eu. Currently it's running on some raw PHP code mixed with Smarty templates, but that's not good enough anymore, so we're coding it from scratch using CakePHP. It's very exciting project to work on. However, it's rather complicated, so we've put quite an effort in planning and designing the whole thing.

Facing so daring project, I had to admit that I've never used proper testing in PHP before, and I had to do something about it. After baking the basic structure of the app I ran into a strange issue with test cases not running properly even without any test methods.

I dug around a bit and dropped the predefined schema in fixture in favour of fetching it from the live database. After more debugging I found out that the schema generation method doesn't work well with composite primary keys!

I'm trying MySQL Workbench for designing the database schema and it creates a composite primary key in HABTM tables over two columns. It makes sense in the design but Cake has a problem. It correctly finds out that both columns are part of a primary key, but it gives them both the AUTO INCREMENT property - that doesn't fly.

It's understandable that Cake doesn't support PK in common tables. But HABTM relationship tables seem to be a different deal to me. There are two possible workarounds:

  • don't specify any PK
  • add a new column called id as a PK and create UNIQUE index on the other two columns

I don't like either of them so I slightly modified the DboSource::createSchema method to look for composite PK and create proper schemas.

I still have this annoying feeling it'll bite me in the ass at some point, but I can't put my finger on when and where exactly. So I will go with it a see how it's working out.