ORM with Validation in Kohana 3
I really like Kohana 3 so far mainly because it feels like someone sliced and diced CodeIgniter into just the pieces I want and added a few major missing components. I have absolutely no complaints about how anything is structured, but the documentation is at a point where it is extremely difficult to get rolling with the framework if you are new to it. One thing that Kohana does very well is ORM and Model level validation, but the pages on how to do this are literally blank at this point.
This article assumes you have a basic understanding of MVC frameworks and how files are organized under Kohana.
I do not have a comprehensive understanding of how Kohana handles this under the hood, and there are likely better ways to write this, but this ended up working fine for me. We'll be setting up a form to create and edit a user. In this particular example we're referring to users as Judges. Our goals are:
- All validation defined within our model inside of a single array using anonymous functions.
- Error messages are not defined in our controller or view
- Minimal PHP in our view that is just outputting values and error messages and does not contain any logic.
- Keeping our controllers as skinny as possible and keeping record creation logic inside of our model.
- Each user has uniquely salted encryption for their password.
- A new user cannot be added if a user already exists with the same email address. A user cannot be edited to have the same address as another user either.
This would be a form that would be used for an administrator to register a new user, rather than let a user register themselves.
You can view all of these files here as well. Comments are inline in each file explain what is going on.
SQL Table Structure