X
    Categories: All Symfony Tutorials, Tips And Guides you needLearn PHP Tutorials, Tips And Guides

Getting Started with Vue.js in Symfony

Reading Time: 6 minutes

Virtually all web application projects, now require a reasonable portion of logic to be executed on the client side. Symfony as a set of reusable PHP components and a web application framework is not exempted from this trend.

As a PHP developer who uses Symfony regularly, I have had a hard time choosing from the numerous JavaScript frontend frameworks available in the market. I had to pick one of the top-rated JavaScript frameworks including Angular, React, Vue and Aurelia.

Symfony Remains Neutral

With the whole hype around which JavaScript framework works best for development, Symfony as a framework remains neutral when it comes to making a choice of a framework that powers the client side logic and activities in web applications. In effect, Symfony doesn’t have a favorite JavaScript framework.

In this article, I will go through the process of enabling and configuring Vue.js within Symfony applications. Part of this process is covered in the official Symfony documentation. But since the docs can be boring at times, I decided to take a practical approach in which I will:

  • Create a Symfony 4 application
  • Install Vue.js and the dependencies
  • Require and process .vue files correctly
  • Create my first Vue component.

So Why Vue?

To begin, Let me state that I have no personal favorites in JavaScript frameworks. I simply use the right tool for the project’s requirements.

Arguably, Vue is one of the best frontend library available today. It is a lightweight and progressive framework that is an ideal fit for all projects.

The Importance of Frontend

I get this question from web developers a lot. A common concern is the addition of complexity to an already complex application. Frontend frameworks like Vue help abstract the complexity and basic application client side logic of any project. This enforces good design patterns and helps create reasonably reusable components. In just few lines of code, you can build a single page application, easily manipulate DOM and make AJAX call to the backend service without hassle.

Prerequisites

I will build a Symfony application that uses Vue as a frontend framework. At first, this application will run locally in the development environment. Afterwards, it can be easily hosted and uploaded to any hosting platform.

To get the best out of this tutorial, a reasonable knowledge of PHP, JavaScript and Object Oriented Programming is advised.

Create A Symfony Application

To start, use composer to quickly set up a new Symfony project. Alternatively, set up a Cloudways account to launch a server and follow this tutorial to set up a Symfony 4 project in just a few minutes.

Symfony 4 comes with Flex, a new way of creating web applications with ease by automating the addition and removal of bundles.

Launch the terminal and use the following command to set up the Symfony app with all the dependencies:

composer create-project symfony/website-skeleton vue-symfony

The above command creates a new project directory called vue-symfony and a few dependencies for a standard Symfony application are downloaded as well.

Before setting up Vue.js, lets install a web server. In the terminal, run the following command:

composer require server -- dev

Next, start the server with:

php bin/console server:run

Navigate to http://localhost:8000/ :

It is possible that you might encounter the following error when you attempt to go to the homepage. This happens because there is no controller to handle the route.

Create the Route and Controller

In the terminal, create a new controller using the following command:

php bin/console make:controller Default

This will create a new controller DefaultController class and a controller method index() inside of it.

Replace the contents of the index() method with:

/**
* @Route("/", name="default")
*/
public function index()
{
   return $this->render('index.html.twig');

}


Next, create a new file .vue-symfony/templates/index.html.twig within the templates folder.

{% extends 'base.html.twig' %}

{% block body %}

   <h3>My Symfony 4 sample project</h3>

{% endblock %}

Go back and restart the server:

Install Vue and its Dependencies

With the introduction of Encore, asset management has become a piece of cake. This asset management tool uses webpack and allows powerful CSS and JavaScript processing, combination, and minification. Before proceeding, ensure that you have Node.js and Yarn package manager installed on your machine.

Using yarn, install Vue and the dependencies.

yarn add --dev vue vue-loader vue-template-compiler

Configure Vue-loader

vue-loader needs to be activated in webpack.config.js. Leave other default settings alone and just enable vue loader through the following code snippet:

var Encore = require('@symfony/webpack-encore'); Encore
   .setOutputPath('public/build/')
   .setPublicPath('/build')
   .cleanupOutputBeforeBuild()
   .enableSourceMaps(!Encore.isProduction())
   .addEntry('js/app', './assets/js/app.js')
   // .addStyleEntry('css/app', './assets/css/app.scss')
   // .enableSassLoader()
   // .autoProvidejQuery()


   // Enable Vue loader
   .enableVueLoader()
;

module.exports = Encore.getWebpackConfig();


Webpack Encore expects an entry point. For this, create a subdirectory named called  js  within assets folder and then add a app.js file inside of it.

// assets/js/app.js
import Vue from 'vue';

import Example from './components/Example'

/**
* Create a fresh Vue Application instance
*/
new Vue({
  el: '#app',
  components: {Example}
});

In the above code snippet, I first imported Vue and Example component. Next, I created an instance of Vue, pass an element where Vue will attach itself to and register the Example component so that it can be accessible.

Create the Vue Component

I will use Vue.js as a widget and include it within Twig template to bring more reactivity to the Symfony application. This is one of the numerous ways of using Vue.js.

Before I compile .vue files, I will create the component. For this, create a new folder assets/js/components and a new component file named  assets/js/components/Example.vue

<template>
   <div>
       <p>This is an example of a new components in VueJs</p>
   </div>
</template>

<script>
   export default {
       name: "example"
   }
</script>

<style scoped>

</style>

Next, I can compile the asset that would be used in the Symfony template and watch the changes by using the following command:

yarn run encore dev --watch

Open the base twig template .vue-symfony/templates/base.html.twig and include the compiled JavaScript files into the base template that would be used in the application.

<!DOCTYPE html>
<html>
   <head>
       <meta charset="UTF-8">
       <title>{% block title %}Welcome!{% endblock %}</title>
       {% block stylesheets %}
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
       {% endblock %}
   </head>
   <body>
   <div id="app">
       {% block body %}{% endblock %}
   </div>

   {% block javascripts %}
       <script src="{{ asset('build/js/app.js') }}"></script>
   {% endblock %}

   </body>
</html>

Show Vue Component Content

Earlier, I created a Vue.js component and registered it for use in the application. This is made possible by including  the custom tag for the newly created component. Edit .vue-symfony/templates/index.html.twig and include the Example component.

{% extends 'base.html.twig' %}
{% block body %}

   <div class="text-center">
       <h3>My Symfony 4 sample project</h3>

       <div class="jumbotron text-center">
           <example></example>
       </div>
   </div>

{% endblock %}


Navigate to the local server (at port 8000) and check out the result:

Final Note

I hope this article has giving you enough enlightenment on how to get started with Vue.js in Symfony apps. So the next time you are faced with the choice of the picking a frontend JavaScript framework, use the tricks you have learned here to get an easy start. The code of this article can be found at Github.

Disclaimer: The opinions and views presented in this article are author’s own, and does not reflect the official policy and views of Cloudways.

Author of the Post: This post is contributed by Olususi Oluyemi. He is a tech enthusiast, programming freak and a web development junkie who loves to embrace new technology. You can find him on yemiwebby.

Shahroze Nawaz :Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. He’s always in search of new frameworks and methods to implement them. Besides his coding life, he loves movies and playing soccer with friends. You can email him at shahroze.nawaz@cloudways.com