Using CakePHP to scaffold a new database table

U

With each new table you create in your database, you will typically need to create a model, controller, and one or more views to get started. CakePHP contains two solutions to get you started creating these files with minimal effort.

Scaffolding allows an application to perform the following four scenarios, known as CRUD: Create, Retrieve, Update, and Delete.

In CakePHP, scaffolding can be done in two different ways. The first way is extremely simple, but doesn’t provide the ability to customize easily. The second way requires a bit of setup time; however, once done, you have full control over customizing any aspect of things.

Getting started with CakePHP Scaffolding

Pre-requisites

  • You have an existing CakePHP project created
  • You have an existing database created (it can be updated)
  • Your application is configured to connect to your database
  • You have some basic database knowledge (to create new tables)
  • Solution 2, requires some basic command line knowledge

Solution 1 – Automagic Scaffolding with CakePHP

For the simple scenario, three things are needed to get started:

  • A new table in your database
  • A basic model
  • A basic controller

Below is an example of a basic users table. This CASE Statement in SQL can be run in a program like phpMyAdmin to create the new table:

[code]
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(150) NOT NULL,
`last_name` varchar(150) NOT NULL,
`email` varchar(150) NOT NULL,
`username` varchar(20) NOT NULL,
`password` varchar(100) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB
[/code]

Once the table is created in your database, you must create a User model that will link to your users table. In the models directory, create a new file called user.php:

[code]
class User extends AppModel {
var $name = ‘User’;
var $displayField = ‘first_name’;
}
[/code]

Finally, a new controller must be created. In the controllers directory, create a new file called users_controller.php:

[code]
class UsersController extends AppController {
var $scaffold;
}
[/code]

In the above example, setting a variable called scaffold tells CakePHP that this is an empty controller and it should automatically provide the CRUD ability. In your web browser the following URLs will allow you to perform the CRUD features:

http://localhost/users

http://localhost/users/add

http://localhost/users/edit?id=

http://localhost/users/delete?id=

http://localhost/users/view?id=

Solution 2 – Scaffolding with the CakePHP Bakery

In this solution, the CakePHP console application bake will be used to create the same functionality as solution 1. However, additional functionality will be added like validation. For this solution, two things are required to get started:

  • A new table in your database
  • PHP CLI (command line interface)

For Linux and Mac users, requirement two should be enabled by default. Windows users, however, require a bit of additional setup. An installation manual has been created by the PHP manual website: http://php.net/manual/en/install.windows.commandline.php

Just like the first solution, below is an example of a basic users table. This SQL statement can be run in a program like phpMyAdmin to create the new table:

[code]
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(150) NOT NULL,
`last_name` varchar(150) NOT NULL,
`email` varchar(150) NOT NULL,
`username` varchar(20) NOT NULL,
`password` varchar(100) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB
[/code]

Once the table has been created, you will need to launch a new terminal or command line console window. Navigate to your CakePHP project, for example: cd \xammp\htdocs\cakephp

To start the bake console application, you run the following command: cake\console\cake bake. The bake console provides 7 different options:

  1. Database Configuration
  2. Model
  3. View
  4. Controller
  5. Project
  6. Fixture
  7. Test Case
  8. For this example, you will be using the Model, View, and Controller. To start, a new model must be created for the users table. Press M to bake a new model. Once the model option is selected, the application will make a connection to your database and retrieve a list of your tables. Find the number that corresponds to the table you wish to bake (in this example it will be the User model) and press enter.

    The first thing the model baking does is look for a display field. Sometimes it is capable of finding it, in this case it probably won’t and will ask you to specify one. Press Y to specify it now. The list of fields are now displayed, select the corresponding number to the field you wish to set as the display field (I’m going to use the first_name which is option 2).

    The next thing to do is specify validation for the model. I personally always like to take the time and setup my validation properly. However, if you are not interested, you can press n and continue on below. I’m going to press y and specify the options now. The application will now proceed through each field in your table and ask how you wish to validate each field. The bake application does a pretty good job at “guessing” what your default validation should be passed on the name, field type, and whether null is allowed. Take a minute a read through the list of options provided and select the validation you want for each field.

    If you follow the conventions from CakePHP on model and database (http://book.cakephp.org/view/903/Model-and-Database-Conventions) 9 times out of 10, you can skim through accepting the default validation values.

    Also, some fields might require more than one validation rule. The username field is an excellent example of this. I would probably specify that it should not be empty and contain a minimum length of 6 characters. For the password field you may wish to select the comparison option if you plan to create a confirm password feature.

    Once you have provided the validation rules for your model the bake application will ask you if you wish to define model associations (belongsTo, hasMany, etc…). If you choose y CakePHP will search your database for potential relationships through a foreign key. As I mentioned earlier, if you follow the CakePHP conventions, the bake application will find all of your relationships without a problem.

    After the associations are setup, a summary of your model is displayed allowing you the option to change something before it is created.

    Finally, the bake application will confirm if you wish to create test fixtures for your new model. If you plan to create a fully testable application with SimpleTest I would encourage you to select y, otherwise, n.

    Now that the model is created, a controller must be created. Unlike solution 1, this controller will contain more than the simple scaffold variable. At the main console screen, select C to create a new controller. Just like with the models, a list of tables are listed that you can create a controller for. Press the number corresponding to the controller you wish to bake.

    Baking controllers can be quite complicated or quite simple. Perhaps complicated is not the right word because it sounds scary. Let’s replace this word with sophisticated because a lot of configurable options are provided: scaffolding, basic class methods, admin routing, which Helpers to include, which Components to include, and use Session flash messages.

    Typically when I am ready to bake my application, I want to keep my controllers simple, but useful, so I will chose n at the interactive mode option. However, feel free to explore that option if you know you are going to use other Helpers and Components apart from the basic ones that are included by default.

    When in non-interactive mode, the first question asked is whether you want to create basic class methods for CRUD – since this is an example of creating basic CRUD functionality, choose y. The next question asked is in regards to admin routing for the basic CRUD functionality. This option is completely up to you. If you plan on creating full admin ability to add, edit, and delete and limit the functionality that a basic user can do, press y; otherwise, n if the basic CRUD functionality is fine for all users.

    Just like with the models, a confirmation screen is displayed to confirm before creating and the question about creating test fixtures for SimpleTest (see above note on a fully testable application).

    The final thing to do is create the views to complete the CRUD interface. Press V to select the views option. Like both the models and controllers, a list of tables is provided that views can be created for. Select the number corresponding to the table you wish to create views for.

    Views must be created last because both a model and controller must exist before the views – the first question is asking whether you have done this already. Since you have already done this; press y to move on. When you created your controller, you were asked about admin routing, this same question is asked again here. Chose the same option as you did before and press enter.

    The baking is now completed and just like solution 1, the following URLs have all been setup to manage users:

    http://localhost/users

    http://localhost/users/add

    http://localhost/users/edit?id=

    http://localhost/users/delete?id=

    http://localhost/users/view?id=

    You might notice that these look exactly the same as solution 1 and why you went through all of this extra work? First off, solution 1 did not contain any validation which can cause some problems when users enter data that gets saved. Secondly, the models, controllers, and views that were created contain fully defined code that can be easily customized to add, change, or remove functionality.

    Summarizing scaffolding with the CakePHP Bakery

    Before you begin scaffolding your application, I would highly recommend performing a full database design first. By doing this, all of your associations and validation options can be fully configured for you. I’ve being done this for many years now and it’s next to impossible to make your initial design perfect (with client changes or additional ideas, etc…), but the more time you put into the database design, the less time you will spend manually adding new associations, validation options, and form fields in your view or table listing!

Other useful articles

About the author

By Jamie

My Books