How to use models and controllers in your webpages.

When first getting started I was quite perplexed as how to build a page that has more than one model and controller attached to it.

If /users/index runs the Users::index() function and the users controller uses the User model then how do I look at data from, say a Profile model on that page? What if I want to have my login function on that page as well?

Well once you get your head around it it’s not that tough, but it took me an embarrassingly long time to get my head around it.

By default the page you go to example.com/users/index is loading the app/views/users/index.thtml file. It’s also running the function index() in app/controllers/users_controller.php and loading the app/models/user.php.

The model tells cake how to interact with the database, and what tables to access.

The controller possibly runs some logic and passes variables to the view.

But the view is in control here. The view loads the html, displays the variables the controller passed (using the set function), and links and forms etc.

So if you want a login form on your index page you simply put that form in your index view and have it submit to /users/login (or whatever function handles the login logic). When you submit that form you’re running that function, not before.

If you want to display information generated (by business logic) in other functions then you can run those functions inside of your index() function. But I think more often you’ll probably want to load data from other models.

I’ll talk about that and the details in my next post.

Leave a Reply

You must be logged in to post a comment.