0
votes

I'm really new to cakephp (3). I have a general question about baking models, views and controllers.

Do I have to completely plan and create the database scheme before baking any m., v. or c?

I'm afraid of overwriting my codes, when I extend my database-scheme. I'm thinking of a situation like this:

I have two tables "Articles" and "Users". I baked mvc-s, having a small but complete website. I tweaked the Users-Model/Entity for some validator-reasons (e.g.).

Now, two weeks later, I want to add a "Group" table, where one user can belong to many groups.

Normally, I could rebake the Users-mvc-files. But that would overwrite my whole website.

Do I make a mistake? Do I have to manually modify the mvc-files when extending tables?

What is the best practice for extending a cakephp-website?

Many thanks in advance.

2

2 Answers

0
votes

Yes, generally you have to plan for database scheme before baking your MVC.

You should manually do the changes if any alter/changes become in the table otherwise the bake will override all the codes you did.

All the very best

0
votes

You could just bake the MVC for the new table, Groups (should be plural), and then update the associations, if any, in other tables. For example, if Users belongs to Groups, after baking the Groups table, you could add:

// in /src/Model/Table/UsersTable.php
$this->belongsTo('Groups', [
    'foreignKey' => 'group_id'
]);

Of course, this assumes you've added the 'group_id' field to the Users table in your database.

This is a fine solution if your table is small and your data model remains fairly static. But if you are working with many tables and you are still regularly making changes to the model, I would suggest doing what I did after blowing away all my controller changes a couple of times.

CakePHP 3 makes very cool use of Elements in it's Controller templates. You can copy the cakephp vendor templates into your src directory, and then provide your additional controller methods (like login()/logout() in UsersController) as elements. Then test for the model and include the appropriate elements for that model.

This way you can bake away and not worry about losing all your changes.