Codementor Events

Nuxt: Decoupling the view and controller in your PHP application

Published Sep 20, 2017Last updated Mar 19, 2018
Nuxt: Decoupling the view and controller in your PHP application

The question

Have you ever wanted to decouple the view and the controller or route in your PHP application?

Such as:

// Render Twig template in route
$app->get('/hello/{name}', function ($request, $response, $args) {
    return $this->view->render($response, 'profile.html', [
        'name' => $args['name']
    ]);
});

Or this:

// UserController.php
namespace Controllers;

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

class UserController {

    public function __construct($container)
    {
        // make the container available in the class
        $this->container = $container;
    }


    public function users(Request $request, Response $response, $args)
    {
        $users = Users::all();
        $this->container->view->render($response, 'list-users.twig', $users);
    }

    //...

}

The controller handles business logic which may change from time to time, and the view may remain unchanged, and vice versa. Separating them enables the fontend developers/designers and backend developers to work on the same project independently. The whole system becomes more maintainable and making unit testing easier. Fixing bugs too gets easier with the decoupled approach. This is a good post that is worth reading.

Nuxt

download.png

Nuxt.js is a framework for creating Universal Vue.js Applications. Simply put, it helps you to build Server Rendered Vue.js applications easily. It abstracts most of the complex configuration involved in managing things like asynchronous data, middleware, and routing. It is similar to Next.js for React and Angular Universal for Angular.

Slim

slim-logo.png

Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs. It is lightweight and easy to get your project started and going without too much dependencies. It is similar to Lumen by Laravel and Silex which is based on Symfony.

The concept

This article shows you a basic concept with an example how you can use Nuxt and Slim to decouple your view and controller for your PHP application. Nuxt will acts as the view for your Slim application which serves as an API.

Getting started

Let's create a simple Slim project and output a message 'Hello World':

// public/index.php

$app = new \Slim\App();
$app->get('/', function (Request $request, Response $response, $args) {
    $data = [
        "status" => 200,
        "message" => "Hello world!"
    ];
    $response->getBody()->write(json_encode($data));
    return $response->withHeader('Content-type', 'application/json');
});
$app->run();

Run it at localhost:8181:

$ php -S 0.0.0.0:8181 -t public

You should see a json output on your browser:

{"status":200,"message":"Hello world!"}

Now, it is time to create a basic Nuxt application and call the PHP application above:

// pages/index.vue

<template>
  <div>
    <h1>{{ message }}</h1>
    <p>This is Nuxt + Slim.</p>
  </div>
</template>

<script>
import axios from '~/plugins/axios'
export default {
  async asyncData () {
    let {data} = await axios.get('/')
    return data
  },
  head () {
    return {
      title: 'Nuxt + Slim'
    }
  }
}
</script>

Run it at localhost:3000:

$ npm start

You should see a HTML rendered page on your browser:

nuxt_slim.png

If you inspect the page, you should see Hello world! is rendered into the HTML tag:

<div>
    <h1>Hello world!</h1>
    <p>This is Nuxt + Slim.</p>
</div>

That's it. You finally have decoupled your view and controller! What the code above in Nuxt does is using Axio, a promise based HTTP client for the browser and node.js, to call localhost:8181:

axios.get('/')

It then gets the data of message from {"status":200,"message":"Hello world!"} and injects it to:

<h1>{{ message }}</h1>

Conclusion

If you are interested in learning more about Nuxt or developing a more complex application, the guide from their official site is a good start. If you are new to Nuxt, this is a great example. You also can use Express.js or Koa.js to replace your PHP application if you want to use Node.js as your backend application instead, check out the examples from their GitHub. The templates for Koa and Express are worth checking out.

Let me know what you think and what you do to decouple your views and controllers in your PHP applications. Any suggestions and errors, please leave a comment below. Hope this basic example is helpful and gives an idea if you ever wondered about the same question. You can get the source code of this example from its repository in GitHub.

Code references

  • https://www.slimframework.com/docs/features/templates.html
  • https://phpocean.com/tutorials/back-end/workouts-with-slim-3-part-5-action-controllers/50
Discover and read more posts from LAU TIAM KOK
get started
post comments1Reply
Ranny Johns
6 years ago

I like the way you help people with your very occurred opinion and suggestion thanks for this and keep posting I am waiting for your next blog. https://printertechsupportnumbers.com/blog/how-to-fix-canon-printer-offline-error/