In a MVC application, integration between controller and views are often a matter of:

class HelloController {
  public function sayHello(Request $request) {
     return new Response($this->templating->render('view', [
       'name' => $request->get('name')

However, there are many frameworks out there which often perform "transparent" integrations of the view with the controller logic. For example, they allow for direct access to the CSRF token by simply writing {{ csrftoken() }} or similar in the view; this happens in an entirely transparent manner.

However, since I'm not using any framework, I'm forced to do something like this for most of the controllers:

$this->templating->render('view', [
  'name' => $request->get('name'),
  'csrf_token' => $this->getCsrfToken()

How can I perform such a transparent integration of controller state like most modern frameworks do?


One way your {{ csrftoken() }} example can be implemented is by parsing the braces, reflecting over the underlying class to find the correct method to call, and replacing the braces and enclosing text with the return value of the method call.

Further Reading
The anatomy of a simple templating engine

| improve this answer | |
  • 1
    I think what the OP means is how frameworks like CakePHP do to automatically load the view and output it without having to interact with it from the controller. – ClemC Aug 26 '17 at 20:52
  • I think Robert already hit the nail on the head. The framework could be reflecting the controller's methods automatically. If the frameworks implements convention over configuration, the methods are mapped via configuration (annotations, attributes, etc) – Laiv Feb 23 '18 at 12:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.