1

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?

0

1 Answer 1

1

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

2
  • 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, 2017 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, 2018 at 12:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.