Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Generating a model with Bake

From: Up and Running with CakePHP

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.

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.

Show transcript

This video is part of

Image for Up and Running with CakePHP
Up and Running with CakePHP

27 video lessons · 4255 viewers

Jon Peck
Author

 

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
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.

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?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

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 preferencesfrom 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.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

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.