Can someone explain the concept of a "controller" to me?

I see the term mentioned quite often but the associated explanations are often quite abstract and seem to make mention of other languages. I am a beginner php programmer, as a first language, so it’s been a little tough for me to digest. A clear explanation of what a controller is and what use it has in php programming would be excellent. Thanks.

This sounds like a simple question but the answer is a little more complex.

A controller is used in an architecture called MVC (Model-View-Controller). In MVC, the controller actually does the least work*. I wrote an introduction to MVC here: MVC in PHP part 1: Hello World which includes a minimal code example.

*Though most PHP implementations don’t follow the standard architecture, but I digress.

However, before asking “what is a controller”, you should be asking “why do I want a controller?”. The answer to this (or in fact, “why do I want a tiered architecture”) is:

It enforces a separation of concerns which means each part of the system has a specific job and can be self-contained. This allows reusability of individual parts. On a practical level, it means you’re not looking through HTML generation code when trying to figure out why your database query isn’t working.

I’m trying to learn best practices, and I have heard that controllers are good for that, so that’s why I am interested.

I’ve got a long way to go and still need to dive into object oriented php, so that may be why the concepts aren’t sticking with me. Do you think that mvc is important for non-OO php programming? I noticed your example was almost purely OO.

OOP makes separation of concerns easier. And while I’m sure MVC is possible without it, I wouldn’t recommend it. Learn OOP frirst. There’s not that much to it. It’s all about thinking about things the other way around and once you get it, there’s no looking back.

I’d suggest not looking into MVC or other advanced topics until you have a good understanding of OOP.

I second that. As with all things new there is always the temptation of getting side tracked during learning or getting carried away, but when it comes to OOP it’s not a good idea to do that but really stay focused until you get it. When you really get OOP it makes all other concepts so much easier!

Otherwise it’s get a bit “the hurrier you go, the behinder you get”.

I would recommend focusing on separation of concerns at this point, even if with functions avoiding OOP entirely its ok. That will give you good basis to start understanding some of the more advanced topics of object oriented programming and design patterns such as MVC. Procedural code itself isn’t evil, not understanding separation of concerns is the problem that results in spaghetti code, procedural or oo.