LanguagesPHPScaffolding with CakePHP - Managing Your Fantasy Football Team

Scaffolding with CakePHP – Managing Your Fantasy Football Team

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Web frameworks are all the rage these days, and for good reason – they save developers a tremendous amount of time and trouble. After all, what developer wouldn’t opt to focus on being creative and making effective use of his skills rather than being burdened with the development of yet another data management interface or building another home-grown templating system? Frameworks remove such repetition by taking care of many of these tedious tasks for you.

For instance, most popular frameworks automate a task common to almost every application: CRUD data operations (Create, Read, Update, and Delete). For instance, if you’re building an application for managing your fantasy football players, at a minimum the application must provide facilities for creating, retrieving, editing, and deleting players. Of course, it would also be useful to know which team the player belonged to, meaning there’s a many-to-one relationship. Finally, the application should keep track of the player’s statistics throughout the course of the year.

Clearly these are necessary features, but implementing them isn’t exactly enthralling. How would you like to have you cake and eat it too?

In this first installment of a two-part series I’ll introduce to how the aptly-named CakePHP framework can make implementing such features a total breeze, using the theme of a fantasy football application as the basis for introduction. In this article I’ll implement the first two aforementioned features, and in the second we’ll build additional features into the application, adding user authentication and allowing others to maintain their roster.

While it’s not required you have prior knowledge of CakePHP to learn from this tutorial, I’ll presume you are familiar with the concept of the MVC architecture. I’ll also leave it to you to install CakePHP. The process is well-documented on the CakePHP website.

Creating the Table Schemas

For purposes of this exercise, the fantasy football application’s data model will be kept fairly basic, consisting of just two tables: players and teams. The respective schemas look like this:

CREATE TABLE players (
   id SMALLINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
   firstname VARCHAR(50) NOT NULL,
   position VARCHAR(25) NOT NULL,
   team_id SMALLINT(6)
)

CREATE TABLE teams (
   id SMALLINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
   name VARCHAR(50) NOT NULL, 
)

Take particular note of the team_id column found in the players table. This is a foreign key, mapping to the primary key in the teams table. The column is named as such because CakePHP is capable of automatically identifying it as a foreign key, and using it to do all sorts of interesting things such as populate listboxes when adding and editing new players. You’ll learn how to do this later in the article.

Next we’ll build the interfaces used to populate these tables, using a feature known as scaffolding.

Setting up Scaffolding

For those of you new to the world of frameworks, I’d venture you’ll find this feature particularly impressive. Remember the aforementioned tedious tasks of creating the templates and logic for creating, modifying, and deleting teams and players? CakePHP creates all of these features for you! Known as scaffolding, CakePHP will parse your table schemas and create the appropriate forms based on their types. While the default templates and logic are likely too basic for enduser use, scaffolding can be particularly advantageous during the application design phase, when the table schemas are often in a state of flux.

In order to successfully implement scaffolding, you’ll need to follow a few conventions:

  • If you’d like to map a foreign key to a table, in our case map a team to a player, the foreign key column name should be named TABLE_id, where TABLE is the name of the foreign table you’re mapping to. Therefore the players table contains a column named team_id.
  • The table you’d like to scaffold should map to a controller defining the variable $scaffold.
  • If you’d like to take advantage of CakePHP’s ability to pick up on table associations, the table you’d like to scaffold should map to a model which defines the association between the relevant tables. CakePHP supports four associations: hasOne, hasMany, belongsTo, and hasAndBelongsToMany. In the case of our example, each player belongs to one team, and therefore we’ll examine the belongsTo association.

We’ve already taken care of the first convention, therefore let’s move on to defining the required controller and models.

Defining the Models and Controller

For scaffolding purposes, creating the controller is amazingly easy; just define the variable $scaffold:

<?php
    class PlayersController extends AppController
    {
        var $scaffold;
    }
?>

Save this code in a file named players_controller.php and place it in the /app/controllers/ directory. Next we’ll define the teams controller. Place the following code in a file named teams_controller.php and save it to the /app/controllers/ directory.

<?php
    class TeamsController extends AppController
    {
        var $scaffold;
    }
?>

Next let’s define the Player model. This is a tad more involved than the controller, but not by much. Place the following code in a file named player.php and save it to the /app/models/ directory.

<?php
    class Player extends AppModel
    {
        var $name = 'Player';

        var $belongsTo = array('Team' =>
                 array('className'    => 'Team',
                     'conditions'   => '',
                     'order'        => '',
                     'foreignKey'   => 'team_id'
                 )
             );
    }
?>

Note the $belongsTo array has been defined, mapping the team_id column to the Team model. Finally, we need to define the Team model so CakePHP knows which column should be displayed as a result of mapping to the teams table. Place the following code in a file named team.php and save it to the /app/models/ directory:

<?php
    class Team extends AppModel
    {
        var $name = 'Team';
        var $displayField = 'name';
    }
?>

Believe it or not, you now have a table insertion, modification, and deletion framework at your disposal for both the players and teams tables! Navigate to the link http://localhost/cake/teams/add and add a few football teams. After adding a few your list view (http://localhost/cake/teams) should look like this:

Next navigate to http://localhost/cake/players/add and add a few players. Notably, you’ll see a dropdown listbox has been created, populated by the previously defined teams! After adding a few players, your list view (http://localhost/cake/players/) will look something like this:

Feel free to play around with the view, edit and delete links to get a feel for these features. While you wouldn’t want to use scaffolding in most production applications, it can be invaluable during during the development phase. You can learn more about CakePHP’s scaffolding features at http://manual.cakephp.org/chapter/scaffolding, and the association types at http://manual.cakephp.org/chapter/models.

About the Author

W. Jason Gilmore (http://www.wjgilmore.com/) is the open source editor for Apress. He’s the author of the best-selling “Beginning PHP 5 and MySQL: Novice to Professional” (Apress, 2004. 758pp.). Along with Robert Treat, Jason is the co-author of “Beginning PHP 5 and PostgreSQL 8: From Novice to Professional”. Jason loves receiving e-mail; so don’t hesitate to write him at wjATwjgilmore.com.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories