<commit_before>---
layout: post
title: "Symfony Tutorial: Building a Blog (Part 2)"
description: Let's use Symfony to build a blog with authentication.
date: 2017-12-23 12:37
category: Technical Guide, PHP, Symfony
author:
  name: <NAME>
  url: https://github.com/GregHolmes
  mail: <EMAIL>
design:
  bg_color: "#3B3B3B"
  image: https://cdn.auth0.com/blog/Symfony/Logo.png
tags:
- symfony
- bootstrap
- authentication
- web-app
- auth0
related:
- 2017-07-26-creating-your-first-symfony-app-and-adding-authentication
- 2016-06-23-creating-your-first-laravel-app-and-adding-authentication
---

**TL;DR:** Symfony is a PHP framework as well as a set of reusable PHP components and libraries. It uses the Model-View-Controller design pattern, and can be scaled to be used in any requirement. It aims to speed up the creation and maintenance of web applications, replacing repetitive code. In this tutorial, I'll show you how to create your very own blog, with content stored in the database and authentication through Auth0. The finished code can be found at this [repository](https://github.com/GregHolmes/symfony-blog).

---

## About Part 1

In the first article, we:

* installed and configured a Symfony installation;
* created two new database tables `author` and `blog_post`;
* allowed users to authenticate with Auth0;
* and ensured the authenticated user created an Author entry before using the system.

In this part of the article we will be covering installing Bootstrap, a framework, to make the blog nicer visually. We will also enhance our blog engine to allow visitors to:

* see a list of blog posts;
* read a specific blog post;
* and find out more about the author.

Authenticated authors will be able to:

* create a new blog post;
* see all of their own blog posts;
* delete their own blog posts from the system.

## Building the Blog Engine
### Installing Bootstrap

In order to install [Bootstrap](https://getbootstrap.com/) we need [Symfony's Webpack Encore](https://github.com/symfony/webpack-encore), which is a simpler way to integrate [Webpack](https://webpack.js.org/) into your application. You can install this by running the following command:

```bash
yarn add @symfony/webpack-encore --dev
```

In the root directory of the project there will be 2 new files (`package.json`, `yarn.lock`) and a new directory (`node_modules`).

Create `webpack.config.js` in the root of the project, this is just the file that contains all of the web pack configurations.

Paste the following code into this file:

```JavaScript
// webpack.config.js
var Encore = require('@symfony/webpack-encore');

Encore
    .setOutputPath('web/build/')
    .setPublicPath('/build')
    .cleanupOutputBeforeBuild()
    .addEntry('app', './assets/js/main.js')
    .addStyleEntry('global', './assets/css/global.scss')
    .enableSassLoader()
    .autoProvidejQuery()

    .enableSourceMaps(!Encore.isProduction())
;

module.exports = Encore.getWebpackConfig();
```

Let's create an SCSS and Javascript file in our assets directory to be used in the configuration above, they can be left empty for now. We will populate them further in the tutorial.

* `assets/js/main.js`
* `assets/css/global.scss`

Running this command, `yarn run encore dev --watch`, will allow us to compile our javascript and CSS into assets to be used in the Symfony templates.

**NOTE** Extra packages may need to be installed. Encore will list these requirements when the command above is run.

Open the base twig template which can be found: `app/Resources/views/base.html.twig` and replace the contents with:

{% highlight html %}
{% raw %}
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>{% block title %}Welcome!{% endblock %}</title>
    {% block stylesheets %}
        <link rel="stylesheet" href="{{ asset('build/global.css') }}" />
    {% endblock %}
</head>
<body>
{% block body %}{% endblock %}
{% block javascripts %}
    <script src="{{ asset('build/app.js') }}"></script>
{% endblock %}
</body>
</html>
{% endraw %}
{% endhighlight %}

We've now included both compiled CSS and empty Javascript files into the base template to be used throughout our app!

In order to make use of Bootstrap we need to install jQuery, so run the command: <commit_msg>Added updates to Part 2 for review<commit_after>---
layout: post
title: "Symfony Tutorial: Building a Blog (Part 2)"
description: Let's use Symfony to build a blog with authentication.
date: 2017-12-23 12:37
category: Technical Guide, PHP, Symfony
author:
  name: <NAME>
  url: https://github.com/GregHolmes
  mail: <EMAIL>
design:
  bg_color: "#3B3B3B"
  image: https://cdn.auth0.com/blog/Symfony/Logo.png
tags:
- symfony
- bootstrap
- authentication
- web-app
- auth0
related:
- 2017-07-26-creating-your-first-symfony-app-and-adding-authentication
- 2016-06-23-creating-your-first-laravel-app-and-adding-authentication
---

**TL;DR:** Symfony is a PHP framework as well as a set of reusable PHP components and libraries. It uses the Model-View-Controller design pattern, and can be scaled to be used in any requirement. It aims to speed up the creation and maintenance of web applications, replacing repetitive code. In this tutorial, I'll show you how to create your very own blog, with content stored in the database and authentication through Auth0. The finished code can be found at this [repository](https://github.com/GregHolmes/symfony-blog).

---

## Symfony Tutorial: About Part 1 and Part 2

In the first article, we:

* installed and configured a Symfony installation;
* created two new database tables `author` and `blog_post`;
* allowed users to authenticate with Auth0;
* and ensured that the authenticated users have `Author` instances associated before using the system.

In this part of the article, we will cover installing [Bootstrap, a UI framework for web applications](https://getbootstrap.com/), to make the blog engine look nicer visually. We will also enhance our blog engine to allow visitors to:

* see a list of blog posts;
* read a specific blog post;
* and find out more about authors.

Besides that, authenticated authors will be able to:

* create a new blog post;
* see all of their own blog posts;
* and delete their own blog posts from the system.

## Building the Blog Engine

### Before Starting

Make sure you have followed all instructions in the first part. However, if for some reason you lost the code created in the first part, or if you want to start here, [feel free to clone this GitHub repository](https://github.com/auth0-blog/symfony-blog-part-1). The following commands will set up the application for you:

```bash
git clone https://github.com/auth0-blog/symfony-blog-part-1
cd symfony-blog-part-1
```

After that, you will have to create file called `.env` in the project root and paste the following into it:

```yml
DATABASE_HOST={DATABASE_HOST}
DATABASE_PORT={DATABASE_PORT}
DATABASE_NAME={DATABASE_NAME}
DATABASE_USER={DATABASE_USER}
DATABASE_PASSWORD={DATABASE_PASSWORD}
AUTH0_CLIENT_ID={AUTH0_CLIENT_ID}
AUTH0_CLIENT_SECRET={AUTH0_CLIENT_SECRET}
AUTH0_DOMAIN={AUTH0_DOMAIN}
```

Note that you will have to replace the values above. Check the first part to understand how to replace them.

__Pro Tip!__ If you do not have a MySQL database available, an easy way to bootstrap one is with Docker:

```bash
docker run --name symfony-blog-mysql \
    -p 3306:3306 \
    -e MYSQL_ROOT_PASSWORD=<PASSWORD>ysecretpassword \
    -e MYSQL_DATABASE=symfony-blog \
    -e MYSQL_USER=symfony-blog-user \
    -e MYSQL_PASSWORD=<PASSWORD> \
    -d mysql:5.7
```

The last thing you will need to do is to use composer to install the dependencies:

```bash
composer install
```

This will trigger a series of questions that you can answer as follows:

```bash
database_host (127.0.0.1): 127.0.0.1
database_port (null): 3306
database_name (symfony): symfony-blog
database_user (root): symfony-blog-user
database_password (null): <PASSWORD>
```

For the questions related to `mailer_transport` and `secret`, you can simply press `Enter` to accept the default values.

### Installing Bootstrap

In order to install [Bootstrap](https://getbootstrap.com/) we need [Symfony's Webpack Encore](https://github.com/symfony/webpack-encore), which is a simpler way to integrate [Webpack](https://webpack.js.org/) into your application.

__NOTE__ If you do not have [Yarn](https://yarnpkg.com), a Javascript package manager, installed, you will need to install and configure this first. So go to their [Installation](https://yarnpkg.com/lang/en/docs/install/) page and follow the instructions for installing and configuring Yarn first.

You can install [Symfony's Webpack Encore](https://github.com/symfony/webpack-encore) by running the following command:

```bash
yarn add @symfony/webpack-encore --dev
```

In the root directory of the project there will be 2 new files (`package.json`, `yarn.lock`) and a new directory (`node_modules`).

Create `webpack.config.js` in the root of the project, this is just the file that contains all of the web pack configurations.

Paste the following code into this file:

```JavaScript
// webpack.config.js
var Encore = require('@symfony/webpack-encore');

Encore
    .setOutputPath('web/build/')
    .setPublicPath('/build')
    .cleanupOutputBeforeBuild()
    .addEntry('app', './assets/js/main.js')
    .addStyleEntry('global', './assets/css/global.scss')
    .enableSassLoader()
    .autoProvidejQuery()

    .enableSourceMaps(!Encore.isProduction())
;

module.exports = Encore.getWebpackConfig();
```

Create the following SCSS and Javascript file in our assets directory to be used in the configuration above, they can be left empty for now. We will populate them further in the tutorial.

* `assets/js/main.js`
* `assets/css/global.scss`

Before we can compile our javascript and CSS files to be used in our Symfony templates, we will need to first install some dependencies. `sass-loader` and `node-sass` are libraries that load SASS/SCSS files and compiles them to CSS, where. To do this run the following command:

```bash
yarn add sass-loader node-sass --dev
```

Now, we can compile our Javascript and CSS into assets to be used by Symfony by running this command, `yarn run encore dev --watch`.

Open the base twig template which can be found: `app/Resources/views/base.html.twig` and replace the contents with:

{% highlight html %}
{% raw %}
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>{% block title %}Welcome!{% endblock %}</title>
    {% block stylesheets %}
        <link rel="stylesheet" href="{{ asset('build/global.css') }}" />
    {% endblock %}
</head>
<body>
{% block body %}{% endblock %}
{% block javascripts %}
    <script src="{{ asset('build/app.js') }}"></script>
{% endblock %}
</body>
</html>
{% endraw %}
{% endhighlight %}

We've now included both compiled CSS and empty Javascript files into the base template to be used throughout our app!

In order to make use of Bootstrap we need to install jQuery, so run the command: 
{'fraction_non_alphanumeric': 0.10455082205468254, 'fraction_numerical': 0.010627668271414297, 'mean_word_length': 4.265423242467719, 'pattern_counts': {'":': 0, '<': 36, '<?xml version=': 0, '>': 36, 'https://': 18, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5827572', 'n_tokens_mistral': 3390, 'n_tokens_neox': 3167, 'n_words': 1342}