MVC Archives - SoftUni Global https://softuni.org/tag/mvc/ Learn Programming and Start a Developer Job Thu, 30 Jun 2022 12:06:56 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.3 https://softuni.org/wp-content/uploads/2022/04/cropped-SoftUni-Global-Logo-Square-notext-32x32.png MVC Archives - SoftUni Global https://softuni.org/tag/mvc/ 32 32 URL Shortener Project – Adding Views, Layout + CSS Styling [Part 2] https://softuni.org/project-tutorials/url-shortener-project-adding-views-layout-css-styling/ https://softuni.org/project-tutorials/url-shortener-project-adding-views-layout-css-styling/#respond Fri, 18 Feb 2022 06:00:00 +0000 https://softuni.org/?p=12378 In our second part of the URL Shortener series, we continue with developing our project. We will create all the views, CSS, and layout page for the project.

The post URL Shortener Project – Adding Views, Layout + CSS Styling [Part 2] appeared first on SoftUni Global.

]]>

In the second part of the tutorial, we will create the user interface for our web application. This will include all the views, CSS, and the layout page. If you haven’t read our previous blog post, where we created our project, you can do it from here.

We start with building the layout page. It allows us to define a common site template that can be inherited in multiple views to provide a consistent look and feel in multiple pages of an application. The layout view eliminates duplicate coding and enhances development speed and easy maintenance.

  • Inside the views folder, we create a layout.pug.

layout.pug

				
					<!DOCTYPE html>
html(lang='en')
  head
    block head
    link(rel='stylesheet', href='/styles.css')
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  body
    header
      a(href='/') Home
      span  | 
      a(href='/urls') Short URLs
      span  | 
      a(href='/add-url') Add URL

    main
      block content
    
    footer
      div © 2022 - URL Shortener
				
			
  • In the head section, we import the .css file that will include our styling. We will create it later inside the public folder.
  • For the body part, we have a header with the navigation of our application. Each anchor tag will lead us to another route.
  • In the main block is the block content that every time will re-render differently depending on our route.
  • We will create a styles.css in our public folder that we made in our previous part.
 

styles.css

				
					body {
  font-family: Arial, Helvetica, sans-serif;
}

header, footer {
  background:rgb(212, 233, 164);
  padding: 8px;
  border-radius: 3px; 
}

footer {
  margin-top: 15px;
}

main {
  margin-left: 10px;
}


table {
  width: 100%;
  border-collapse: collapse;
  background-color: #f5fff5;
}

table th, table td {
  border: 1px solid #ddd;
}

table th {
  padding: 12px 8px;
  text-align: left;
  background-color: rgb(107, 182, 109);
  color: white;    
}

table td {
  padding: 8px;
  overflow-wrap: anywhere;
}

table tr:nth-child(even) {
  background-color: #dff0de;
}

table tr:hover {
  background-color: rgb(198, 207, 180);
}


form table {
  width: 100%;
  max-width: 600px;
}

form table td:nth-child(1) {
  width: 10%;
  white-space: nowrap;
}

main form input {
  width: 100%;
  min-width: 100px;
  box-sizing: border-box;
}

				
			
  • If we want to add more pages, we need to set up the routes in our controller. As we did in the previous part, we create different functions for each  route. In the mvc-controller.js, we  will expand the functionality with new functions.

mvc-controller.js

				
					function setup(app, data) {
  app.get('/', function(req, res) {
        //  Same as before
  });

  app.get('/urls', function(req, res) {
    let model = { urls: data.urls };
    res.render('urls', model);
  });

  app.get('/add-url', function(req, res) {
    let model = { url: "", code: "newCode" };
    res.render('add-url', model);
  });

  app.post('/add-url', function(req, res) {
    res.redirect('/urls');
  });

}

function date2text(inputDate) {
  let date = inputDate.toISOString().split('.')[0];
  date = date.replace('T', ' ');
  return date;
}

module.exports = { setup };
				
			
  • With the first function, we will get the view with all the URLs. It will be the same as the home view functionality.
  • The second function will load the view for the create page. We will access it with the “/add-urlroute.
  • The next third function will have the same route as the previous but with a different type of request. In the app.get(‘/add-url’, … ) we request the view, but with app.post(‘/add-url, …) we will send data to the server. They are on the same route, but we send different types of requests.
  • We will add a helping function data2text() that will be outside of the setup() function. It will help us later.
  • What we need to do next is to create .pug view. First, we will add the urls.pug inside our views folder. We add the following code inside it:

urls.pug

				
					extends layout.pug

block append head
  title='Short URLs'

block content
  h1 Short URLs
  table
    thead
      tr
        th Original URL
        th Short URL
        th Date Created
        th Visits
    tbody
      each url in urls
        tr
          td 
            a(href=`${url.url}` target="_blank") #{url.url}
          td
            a(href=`${url.shortUrl}` target="_blank") #{url.shortUrl}
          td #{url.dateCreated}
          td #{url.visits}
				
			
  • In this view, we will have an HTML table featuring all the records that we request from the server. They are bound to the urls variable. To access each element separately we need to iterate over the collection with a for-each loop. Each row will be with data for a specific record, and every cell with a value for a specific property of the object.

If we start the project and go to the ‘/urlsroute, this will visualize: 

urls-view

  • In next part we will add the add-url.pug view. We add it inside the views folder.

add-url.pug

				
					extends layout.pug

block append head
  title='Add Short URL'

block content
  h1 Add Short URL
  form(method='POST' action='/add-url')
    table
      tr
        td
          label(for='url') URL: 
        td
          input#url(type='text', name='url', value=`${url}`)
      tr
        td
          label(for='code') Short Code: 
        td
          input#code(type='text', name='code', value=`${code}`)
      tr
        td(colspan="2")
          button(type='submit') Create
				
			
  • In this view, we add a form that is with a POST method, and an action points to ‘/add-url‘. To explain what this does, after pressing the submit button, the server will request the app.post(‘/add-url’, …) function that we have typed inside our mvc-controller.  In the next parts, we will add the functionality that saves the record inside the database.
  • Inside the form, we have two input fields. Inside each field, the user will type the values for the URL he needs to create.
  • In the end, it is important for the button to be of type submit. This will submit the form to the server.

If you have done everything correctly, going to the ‘/add-urls‘ route will display you this page:

add-url-view

After completing all the steps, your project will have a user interface that supports different types of screens. If we go to our two new routes ‘/urls‘, and ‘/add-urls‘ you will access the two new pages that we have added. On the ‘/add-urls‘ route, if you submit the form with the required data, you will send a POST request to the server. In the next parts, we will be able to save this information on the server and display it inside the ‘/urlsroute.

Lesson Topics

In this tutorial we cover the following topics:
  • Building the Layout Template in Pug
  • Adding CSS Styles
  • Implementing the “View Short URLs Table”
  • Styling the Table
  • Implementing the “Add URL” Form
  • CSS Styling for Small Screens

Lesson Slides

The post URL Shortener Project – Adding Views, Layout + CSS Styling [Part 2] appeared first on SoftUni Global.

]]>
https://softuni.org/project-tutorials/url-shortener-project-adding-views-layout-css-styling/feed/ 0
URL Shortener Project – Creating the App Structure [Part 1] https://softuni.org/project-tutorials/url-shortener-project-creating-the-app-structure/ https://softuni.org/project-tutorials/url-shortener-project-creating-the-app-structure/#respond Thu, 10 Feb 2022 06:00:00 +0000 https://softuni.org/?p=12280 In this article of the Project Tutorial series, we will create a simple URL Shortener, using JavaScript, Node.js, Express.js and Pug

The post URL Shortener Project – Creating the App Structure [Part 1] appeared first on SoftUni Global.

]]>

In this tutorial, we will create our URL Shortener using JavaScript. We will be using Expres.JS for creating the server-side web application and Pug as a template engine. This tutorial will be split into several parts, and in each part, we will further develop our project. In the end, we will have a fully working Multi Page Application (MPA).

After we initialize our project, we need to split our code logic into different folders. We create folders for:

  • data
  • controllers
  • views
  • public

In our main directory we have an index.js file that is automatically generated by repl.it. You don’t need to install manually any libraries because they will be added automatically when you start the project.

First, in our index.js we need to add the following code:

 

index.js

				
					const express = require('express');
const app = express();
app.use(express.static('public'))
app.set('view engine', 'pug');

const data = require("./data/app-data");
data.seedSampleData();

const mvcController = require(
  "./controllers/mvc-controller");
mvcController.setup(app, data);

let port = process.argv[2];
if (!port) port = process.env['PORT'];
if (!port) port = 8080;

app.listen(port, () => {
  console.log(`App started. Listening at http://localhost:${port}`);
})
.on('error', function(err) {
  if (err.errno === 'EADDRINUSE')
    console.error(`Port ${port} busy.`);
  else 
    throw err;
});
				
			
  • In the first row, we import the ExpressJS node module. Then we bind it to a constant and use it to make static our public folder. Doing this will allow us to use the public folder from any part of our application.
  • We will also set our view engine to pug. This will render all .pug files we set as views.
  • We define constant named data and invoke the function. seedSampleData() inside it. We will create them later. Every time our project is started this function will be initialized.
  • Our next task is to tell the index.js that our MVC-controller exists and set up it.
  • We set our virtual port for repl.it to 8080, and tell the program to listen to this port.
  • If there is an error, it will be automatically displayed on the server’s console.

app-data.js

				
					let urls = [];

function seedSampleData() {
  urls.length = 0; // cleanup
  urls.push({
    url: "https://softuni.org",
    shortCode: "su",
    dateCreated: new Date("2022-02-19T16:41:56"),
    visits: 86
  });
  urls.push({
    url: "https://nakov.com",
    shortCode: "nak", 
    dateCreated: new Date("2022-02-17T14:41:33"), 
    visits: 160
  });
}

module.exports = {
  urls,
  seedSampleData
};
				
			
  • In our data folder we create an app-data.js file. In it is we create our seed of data. We add an empty array that we fill with the seedSampleData() function.
  • In our function we have 2 different objects {} that we push into the urls array.
  • This is a temporary solution and in our next parts will be changed with a real database.

mvc-controller.js

				
					function setup(app, data) {
  app.get('/', function(req, res) {
    let visitors = 0;
    for (const url of data.urls) {
      console.log(url);
      visitors += url.visits;
    }
    let model = { urls: data.urls, visitors };
    res.render('home', model);
  });
}

module.exports = { setup };
				
			
  • Inside our controller folder we create the  mvc-controller.js file. Inside it, we add the function setup() that receives the app and data
  • When our server recieves a GET request with a URL that equals ‘/’, it will invoke the following function.
  •  We iterate over the collection of data and bind it into the model variable. 
  • Then, we render the following view with the data attached to it. 
  • After we are done, we export the function so that the index.js can run it correctly.

home.pug

				
					h1 URL Shortener
ul
  li Short URLs: <b>#{urls.length}</b>
  li URL visitors: <b>#{visitors}</b>    
				
			
  • Finally, we create our home.pug view inside the views folder. That is the html page that will load when the user goes to the ‘/’ URL, that we defined in our controller.
  • We have an unordered list( ul ), in which we have two rows( li ). The first is for the count of our URLs, and the next is the total sum of all visitors summed from all 2 records.
  • If we want to print the data bound to the variable visitors, we must add hashtag # and braces { } around it so that our compiler knows that this isn’t a regular HTML text.

url-first-part-final-lookAfter completing all the steps you will have a simple working Multi Page Application. If you start your project, you will see that everything that we have done is working correctly. We are using the MVC architecture, and we have split the project into different folders and functions for better understanding. This way  you can clearly see where each part is located. Keep up with our parts and see how our project grows more.

Lesson Topics

In this tutorial we cover the following topics:
  • URL Shortener: App Walkthrough
  • Project Structure
  • Creating the App Structure

Remember that coding is a skill, which should be practiced. To learn to code, you should write code every day for a long time. Watching tutorials is not enough. You should code! 

We would love to hear from you, so leave a comment below saying what topics you would like to see next.

Register now and take your free resources right away! Become a member of the SoftUni Global Community and communicate with other students and mentors and get help for FREE.

After registering, you will get access to thе project code.

Lesson Slides

The post URL Shortener Project – Creating the App Structure [Part 1] appeared first on SoftUni Global.

]]>
https://softuni.org/project-tutorials/url-shortener-project-creating-the-app-structure/feed/ 0
What You Need to Know about Back-End Technologies [Dev Concepts #23] https://softuni.org/dev-concepts/what-you-need-to-know-about-back-end-technologies/ https://softuni.org/dev-concepts/what-you-need-to-know-about-back-end-technologies/#respond Tue, 11 Jan 2022 06:10:00 +0000 https://softuni.org/?p=10418 In this video, we will get familiar with Back-End technologies and concepts like Databases, ORM and MVC Frameworks, Rest, Containers and Docker.

The post What You Need to Know about Back-End Technologies [Dev Concepts #23] appeared first on SoftUni Global.

]]>

In this lesson, we take a look at Back-End technologies in software development. That is a technical term that deals with server-side operations, including CRUD functions with database and server logic. Meanwhile, Front-End development is programming which focuses on the visual elements of a website or app that a user will interact with.iceberg-front-back-end

Back-End technologies are essential in the development of software projects. Whether you are a startup founder, or a corporate decision-maker, selecting the right Back-End technology is crucial to determine your project success. Choosing the correct Back-End technologies can guarantee scalability, functioning speed, and instant response to customers’ needs.

In our video, we explain foundation concepts that aspiring developers shouldn’t miss. Keep up with the videos, and you will learn about:

  • Databases: They are a place for storing our data but in an organized structure.  Data is organized and stored in the form of tables. A table contains rows and columns. Each row in a table is a record, and column a field that describes the row.  Read our article about them here.
  • ORM: This is short of Object Relational Mapping. It is the idea of writing queries using your favorite programming language. You interact with a database using your language of choice instead of SQL. Read our article about them here.

mvc-logo

  • MVC: The term stands for ModelViewController. It is a design pattern used to help us build frameworks for applications. The MVC splits the application into three different sections. Each section represents one word from the abbreviature. Each component has a specific responsibility and has a link to the others. Read our article about them here.
  • Web Services and APIsWeb Service is a network-based resource that fulfills a specific task. On the other hand, API is an interface that allows you to build on the data and functionality of another application. There is an overlap between the two. WEB services are APIs, but APIs can be offline. Many public APIs are transparent, with open documentation and self-service portals for quick developer onboarding. On the other hand, Web Services are not open source. Instead, they tend to offer specific data and functionality to partners.

web-vs-api

  • REST and RESTful Services: REST is a set of architectural constraints, not a protocol or a standard. API developers can implement REST in a variety of ways. When a client request is made via a RESTful API, it transfers a representation of the state of the resource to the requester or endpoint. This information, or representation, is delivered in one of several formats via HTTPRestful Web Services is a lightweight, maintainable, and scalable service built on the REST architecture. It also exposes API from your application in a stateless manner to the calling client. The calling client can perform predefined operations using the Restful service.rest-diagram
  • Virtualization, Containers, and Docker: Virtualization is a relatively new technology that allows creating a completely isolated machine from scratch, all in software. Nowadays, companies are starting to prefer Docker. It s a tool that uses containers to make the creation, deployment, and running of applications a lot easier. Read our article about them here.docker-image-vm

Hopefully, reading all this about Back-end technologies will help you in making the right decision. No matter what language you are using, all of those concepts are the same. For every aspiring programmer, it’s a must to know all of the topics. If you want to learn more about the differences between Front-End, Back-End, and Full-Stack technologies you can read our article here.

Lesson Topics

In this tutorial we cover the following topics:
  • Front-End and Back-End
  • Databases
  • ORM
  • MVC
  • ORM
  • Web Services and APIs
  • Rest and RESTful Services
  • Virtualization, Containers, and Docker

 

Lesson Slides

The post What You Need to Know about Back-End Technologies [Dev Concepts #23] appeared first on SoftUni Global.

]]>
https://softuni.org/dev-concepts/what-you-need-to-know-about-back-end-technologies/feed/ 0
Model-View-Controller (MVC) [Dev Concepts #20] https://softuni.org/dev-concepts/model-view-controller-pattern/ https://softuni.org/dev-concepts/model-view-controller-pattern/#respond Fri, 17 Dec 2021 11:47:00 +0000 https://softuni.org/?p=9468 In this video from the Dev Concepts series, we take a look at the MVC pattern!

The post Model-View-Controller (MVC) [Dev Concepts #20] appeared first on SoftUni Global.

]]>

In this episode, we take a look at the MVC pattern. In short, MVC stands for ModelViewController. It is a design pattern used to help us build frameworks for applications. The MVC splits the application into three different sections. Each section represents one word from the abbreviature.
The lesson includes a small example, which uses the MVC pattern, so make sure to check it out.

mvc-logo

What are Models, Views, and Controllers?

Each component has a specific responsibility and has a link to the others. That creates a solid structure for our web application.

  • Model is the lowest level, responsible for maintaining the data. Each model has a connection to the database and can have relationships to other models. If any data changes, the model will notify the controller.
  • The view is the only part of the app the user interacts with directly. It represents the visualization of the data that a model contains. The model never directly communicates with the view.
  • A controller is the go-between for model and view. It relays data from browser to app and from app to browser. The controller receives user input, translates it to match the model, and then passes those inputs onto a view.

Using the MVC pattern correctly can help you as a developer. It ensures a smooth and easy-to-follow user experience. Although it takes time to understand how MVC works, it will pay off when creating future applications.

In the end, MVC is not hard to understand. Just keep in mind these key points:

  • MVC is an architectural pattern consisting of three parts: Model, View, Controller.
  • Model: handles data logic.
  • View: displays the information from the model to the user.
  • Controller: controls the data flow into a model object and updates the view whenever data changes.

Lesson Topics

In this video we review the following topics:
  • Model-View-Controller Patter
  • Web MVC Frameworks

Lesson Slides

The post Model-View-Controller (MVC) [Dev Concepts #20] appeared first on SoftUni Global.

]]>
https://softuni.org/dev-concepts/model-view-controller-pattern/feed/ 0