Up and Running with CakePHP
Illustration by Don Barnett

Up and Running with CakePHP

with Jon Peck

Video: Generating a model with Bake

To save time, I'm going to use the console command cake bake to generate the code for the models. Once generated, I'll review the created code to give context about what it means. We'll also customize the generated code. Models can be created manually, but if there's a mechanism that'll save time that doesn't introduce overhead, why not use it? It's better to save time by generating the code. I'm going to switch the terminal. Then, from the project root, I'm going to evoke cake bake.

Start your free trial now, and begin learning software, business and creative skills—anytime, anywhere—with video instruction from recognized industry experts.

Start Your Free Trial Now
please wait ...
Watch the Online Video Course Up and Running with CakePHP
1h 40m Intermediate Sep 30, 2013

Viewers: in countries Watching now:

Speed up your development with CakePHP, the popular open-source PHP framework. In this course, author Jon Peck builds a magazine cataloging system while explaining how to work with the Model-View-Controller (MVC) development pattern.

The course demonstrates how to install and configure CakePHP, describing the layout and components. Then, leveraging the Bake console, Jon shows how to generate and customize code, and explores form validation, database persistence, and even image uploads. By developing a complete, functional application, you'll have the foundation you need to build your own applications with CakePHP.

Topics include:
  • What is CakePHP?
  • Installing and configuring CakePHP
  • Generating a model with Bake
  • Linking models together
  • Generating a controller
  • Saving a model from the controller
  • Displaying a model with a view
  • Debugging a failed save
  • Using helpers to generate HTML
  • Uploading files and displaying images
Subject:
Developer
Software:
PHP CakePHP
Author:
Jon Peck

Generating a model with Bake

To save time, I'm going to use the console command cake bake to generate the code for the models. Once generated, I'll review the created code to give context about what it means. We'll also customize the generated code. Models can be created manually, but if there's a mechanism that'll save time that doesn't introduce overhead, why not use it? It's better to save time by generating the code. I'm going to switch the terminal. Then, from the project root, I'm going to evoke cake bake.

But this time, I won't specify what I'm baking. Bake will produce a menu of everything that can be generated. What would I like to bake? M for model. Using the database connection Cake will scan the database for table names that it can recognize with plural names. In this case there are two tables, publications and issues. So it's presenting an operation to generate both as a model. An issue can be associated with a publication so I'll create the publication model first. Type two for publication.

The next question is asking what the primary key of the table is. In this case bake guessed it correctly. Publication id, so I'll just press enter. After the primary key is a display field which is used as the human readable label for the record. Cake will recognize columns named title and name. But since it's named publication name, it didn't recognize it. Would I like to choose one? Yes. There are two columns to choose from, lets pick the publication name. Two. Now that the primary key and display field have been specified, do I want to specify validators for user input? Of course, yes. This helps enforce the concept that model should be responsible for data validation, and to ensure that models should conform to the business rules of the application.

I'll get into validation in greater detail in a moment. So, for now, let's add some validation rules. The first field to validate is the primary key. Which is just an integer. I don't ever want users to manually specify a primary key, so I'm going to choose three for blank. Do I want to add another validation rule? Not at this time. The second field, publication name, also requires validation. This time, I'm going to allow humans to specify input. Your first impulse, which I'll admit was mine, was to start with alphanumeric.

However, this only allows letters and numbers. Spaces are not allowed, and cannot be allowed. Therefore, I'm going to specify a custom rule, and will specify a regular expression manually later. While the interface says that I can just provide a regex string, at the time of this writing, the Bake application doesn't handle it correctly. Therefore, I'm going to choose seven for custom. Notice that bake won't prompt me for a regular expression. I'll have to add that later. Then, I'll add a second rule, so yes.

Then 24 for not empty. As a publication must have a name. I'll specify a maximum length to prevent infinitely long names. So I'll choose yes, then 18, for max length. Notice again that I wasn't prompted to specify what the maximum length was. I'll have to do that manually. That's all I need for validation, so I'll say no, no more rules. Following validation are model associations. At this time, I don't need to specify any, so I'll just say no.

That's the final question, and I'll be presented with an overview of what I chose. Does everything look correct? If it looks good, say Y for yes. Cake will bake a model class for publication, which means it generates the necessary code and reports the path. It'll ask if I want to create unit tests. I do not, as that is a more advanced topic. When it's done, just press Q to quit. Now that Cake has generated the code, let's take a look at what we baked, by switching back to the IDE.

Navigate to App>Model. There's a new file in here called Publication.PHP. It's named the same as the model. Opening the file, I can see at the very top there's a static method call. While CakePHP lazy loads classes, meaning they're only loaded when they're needed. The autoloader needs to find the class. Line two, this line tells the app what package the class can be found in. App uses takes two parameters, the class and the package.

So, the first parameter in app model is the class, and model is the package. Next, is the class definition, which extends CakePHP's core. There are two properties defined. Primary key, which contains the column name, publication ID, and display field, containing publication name. Note that both properties use lower CamelCase convention, where the first word is lowercase and the remaining words start with the uppercase. There aren't any explicit declarations for properties that are in the database because there isn't any need to.

Cake does this automatically. Following those two field definitions are the validation rules. The rules are defined in a nested array. The first level is the field that is being validated, followed by the validator name, and any rules that apply. Note that this section is pretty much a placeholder. Other than specifying that the rule is blank, everything else is commented out. Before we proceed, let's learn more about data validation.

There are currently no FAQs about Up and Running with CakePHP.

 
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ .

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

* Estimated file size

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Up and Running with CakePHP.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member ?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferences from the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Learn more, save more. Upgrade today!

Get our Annual Premium Membership at our best savings yet.

Upgrade to our Annual Premium Membership today and get even more value from your lynda.com subscription:

“In a way, I feel like you are rooting for me. Like you are really invested in my experience, and want me to get as much out of these courses as possible this is the best place to start on your journey to learning new material.”— Nadine H.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.