That’s right, I’m still on my CakePHP journey. I’ve been spending quite a bit of time now trying to match what I want to build with how to go about doing it in CakePHP. We all know that the blog example is pretty simplistic – a real world app won’t be quite so straightforward. At the moment, I’m trying to build up an intranet of sorts, with lots of different independant apps, and it’s driving me crazy… How would I structure the it? Should I use ‘plugins’? The folders, the views etc. Yes, it’s all still a big mess.
In any case, I found that CakePHP has a really nifty feature that really helps with sorting out the mess, and it’s called “scaffolding”.
Scaffolding is Cake’s way of quickly building up a basic application that can “Create”, “Retrieve”, “Update” and “Delete” (or CRUD) objects, with just a few simple lines of code.
All we need to do is to setup your database table, the model and the controller, and that’s it – you can browse your database, add new entries, delete, update etc. All the basic CRUD functionality you need.
Following on from my last posting on ‘associations’, let’s add in Authors to our blog application.
Create the ‘authors’ database table
First thing we should do is to create a table called ‘authors’ with a primary key id and a name field, and insert one sample row.
CREATE TABLE `authors` ( `id` INT( 10 ) UNSIGNED NOT NULL AUTO_INCREMENT , `name` TEXT NOT NULL , PRIMARY KEY ( `id` ) ); INSERT INTO `comments` (`id` ,`name` ) VALUES ( NULL , 'Jeremy Clarkson');
Create an ‘Author’ model
Next, we should create our model at this location
/app/models/author.php with something like this:
Create the controller with scaffolding
Now, we can go ahead to create the controller at this location
/app/controllers/authors_controller.php. But this controller is going to be different from our previous examples. It will only contain 1 line within the AuthorsController class:
Scaffolding in action!
Once you have done the above, point your browser to your authors url. In my case, it’s
http://localhost/authors, and what I see is a table listing with 1 entry – Jeremy Clarkson.
That’s it. You can now perform all the basic CRUD actions, all from 1 line of
A word of warning
Cake’s documentation has made it very clear that scaffolding is not a production solution. It’s just a quick way for you to do some prototyping. Once you have your prototype, you should be able to be able to swap out the scaffold with your own code, as your codes will take precedence over the ones from the scaffold.
I’m going to end the posting here, even thought we should, by right, link up the authors and posts table using Associations. If you have read my previous CakePHP post, you should know how to go about doing that.