DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Mocking Dependencies and AI Is the Next Frontier in Vue.js Testing
  • Serving a Vue.js Application With a Go Backend
  • How To Become a Symfony Certified Engineer: Your Path to Expertise in the Software Industry
  • Build Full-Stack Web App With Firebase, Angular 15, React.js, Vue.js, and Blazor [Video]

Trending

  • Scaling InfluxDB for High-Volume Reporting With Continuous Queries (CQs)
  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis
  • Rust and WebAssembly: Unlocking High-Performance Web Apps
  • Comparing SaaS vs. PaaS for Kafka and Flink Data Streaming
  1. DZone
  2. Coding
  3. Frameworks
  4. Symfony Routes in Vue.js (SPA)

Symfony Routes in Vue.js (SPA)

This article discusses how to pass URLs from Vue.js to Symfony with simple rerouting options. We discuss what each platform is and how to connect them.

By 
Dariusz Włodarczyk user avatar
Dariusz Włodarczyk
·
Apr. 27, 21 · Code Snippet
Likes (2)
Comment
Save
Tweet
Share
9.5K Views

Join the DZone community and get the full member experience.

Join For Free

Vue.js + Symfony

Symfony comes with the "out-of-box" routing logic, which works flawlessly when using it in PHP or in Twig. However, once the frontend control is fully handled to the Vue.js (SPA), the solution for passing the URLs to the JavaScript is no longer an option.

The official idea/way of passing the URLs has been described in the Symfony documentation in the section “Generating URLs in JavaScript”, which is simply:

JavaScript
 




x


 
1
const route = "{{ path('blog_show', {slug: 'my-blog-post'})|escape('js') }}";



With a new project (or more like an extension of an already existing project), I started to wonder if there is actually a way to share Symfony routes in Vue.js. I’ve already in a big, over 2 years old private project, in which the urls are simply hardcoded in the frontend — with this I wanted to find a way out to replicate the routing in the Vue.js.

Actually the solution for this is pretty simple, and allows to easily replicate the url generating logic available in php:

PHP
 




xxxxxxxxxx
1


 
1
$this->router->generate('user_profile', [
2
    'username' => $user->getUsername(),
3
]);



Handling Routes for Vue.js

The difference in Routes Structure

The foremost important difference between Symfony and Vue.js routes is the way that parameters in URLs are handled.

While Symfony uses this annotation:

PHP
 




xxxxxxxxxx
1


 
1
"/module/passwords/group/{id}"



Vue.js uses this one:

JavaScript
 




xxxxxxxxxx
1


 
1
"/module/passwords/group/:id"



Generating Routes for Vue.js

All available routes can be loaded and afterwards inserted into the json file, which is a perfect solution to read later on with Vue.js. For this, I’ve created a Symfony Command:

PHP
 




xxxxxxxxxx
1
117


 
1

          
2
<php
3
namespace App\Command\Frontend;
4

          
5
use App\Controller\Core\ConfigLoader;
6
use App\Controller\Core\Services;
7
use Exception;
8
use Symfony\Component\Console\Command\Command;
9
use Symfony\Component\Console\Input\InputInterface;
10
use Symfony\Component\Console\Output\OutputInterface;
11
use Symfony\Component\Console\Style\SymfonyStyle;
12
use Symfony\Component\Routing\RouterInterface;
13
use TypeError;
14

          
15
/**
16
 * This command handles building json file which consist of backed (symfony) routes,
17
 * This way the urls can be changed any moment without the need to update these also on front,
18
 * Just like it works in symfony - names must be always changed manually, same goes to logic related to parameters
19
 *
20
 * Class BuildRoutingMatrixCommand
21
 * @package App\Command\Frontend
22
 */
23
class BuildRoutingMatrixCommand extends Command
24
{
25

          
26
    protected static $defaultName = 'pms-io:build-frontend-routing-file';
27

          
28
    /**
29
     * @var Services $services
30
     */
31
    private Services $services;
32

          
33
    /**
34
     * @var SymfonyStyle $io
35
     */
36
    private SymfonyStyle $io;
37

          
38
    /**
39
     * @var RouterInterface $router
40
     */
41
    private RouterInterface $router;
42

          
43
    /**
44
     * @var ConfigLoader $configLoader
45
     */
46
    private ConfigLoader $configLoader;
47

          
48
    public function __construct(
49
        Services $services,
50
        RouterInterface $router,
51
        ConfigLoader $configLoader,
52
        string $name = null)
53
    {
54
        parent::__construct($name);
55
        $this->configLoader = $configLoader;
56
        $this->services = $services;
57
        $this->router = $router;
58
    }
59

          
60
    /**
61
     * Initialize the logic
62
     *
63
     * @param InputInterface $input
64
     * @param OutputInterface $output
65
     */
66
    public function initialize(InputInterface $input, OutputInterface $output)
67
    {
68
        $this->io = new SymfonyStyle($input, $output);
69
    }
70

          
71
    /**
72
     * Execute the main logic
73
     *
74
     * @param InputInterface $input
75
     * @param OutputInterface $output
76
     * @return int
77
     * @throws Exception
78
     */
79
    public function execute(InputInterface $input, OutputInterface $output): int
80
    {
81
        $this->services->getLoggerService()->getLogger()->info("Started building routing file for frontend");
82
        {
83
            try {
84

          
85
                $routesNamesToPaths = [];
86
                $routesCollection = $this->router->getRouteCollection()->all();
87

          
88
                foreach ($routesCollection as $routeName => $route) {
89
                    $routesNamesToPaths[$routeName] = $this->normalizePathForVueRouter($route->getPath());
90
                }
91

          
92
                $jsonRoutesMatrix = json_encode($routesNamesToPaths);
93
                file_put_contents($this->configLoader->getConfigLoaderPaths()->getRoutingFrontendFilePath(), $jsonRoutesMatrix);
94

          
95
            } catch (Exception | TypeError $e) {
96
                $message = "Something went wrong while building the file";
97
                $this->services->getLoggerService()->logException($e, [
98
                    "info" => $message,
99
                    "calledFrom" => __CLASS__,
100
                ]);
101
                throw new Exception($message);
102
            }
103

          
104
        }
105
        $this->services->getLoggerService()->getLogger()->info("Started building routing file for frontend");
106

          
107
        return Command::SUCCESS;
108
    }
109

          
110
    /**
111
     * Handles transforming paths to make them work with vue
112
     */
113
    private function normalizePathForVueRouter(string $path): string
114
    {
115
        //While Symfony uses {param}, vue router uses :param
116
        $normalizedPath = preg_replace("#\{(.*)\}#", ":$1", $path);
117
        return $normalizedPath;
118
    }
119
}



Afterwards all that has to be done is loading the generated file in the Typescript Class:

Plain Text
 




xxxxxxxxxx
1


 
1
import * as routes from '../../../../config/frontend/routes.json';



and adding a method to load the url by route name and to replace the provided parameters:

TypeScript
 




xxxxxxxxxx
1
38


 
1
   /**
2
     * Will get url path for route name
3
     * Exception is thrown is none match is found
4
     *
5
     * @param routeName       - name of the searched route
6
     * @param routeParameters - array of parameters that need to be replaced in the route
7
     *                          if not matching parameter is found then warning log is thrown and next
8
     *                          parameter will be processed
9
     */
10
    public static getPathForName(routeName: string, routeParameters: Object = {}): string
11
    {
12
        // get route
13
        let matchingRoutePath = routes[routeName];
14
        if( StringUtils.isEmptyString(matchingRoutePath) ){
15
            throw {
16
                "info"         : "No matching route was route was found for given name",
17
                "searchedName" : routeName,
18
            }
19
        }
20

          
21
        // replace params
22
        let keys = Object.keys(routeParameters);
23
        keys.forEach( (parameter) => {
24

          
25
            if( !matchingRoutePath.includes(":" + parameter) ){
26
                console.warn({
27
                    "info"      : "Provided path does not contain given parameter",
28
                    "parameter" : parameter,
29
                })
30
            }else{
31
                let value         = routeParameters[parameter];
32
                matchingRoutePath = matchingRoutePath.replace(":" + parameter, value);
33
            }
34

          
35
        })
36

          
37
        return matchingRoutePath;
38
    }



It’s possible to make things even better just by adding the constants in Typescript (static readonly):

TypeScript
 




xxxxxxxxxx
1
15


 
1
/**
2
 * @description This class contains definitions of INTERNAL api routes defined on backend side
3
 *              there is no way to pass this via templates etc so whenever a route is being changed in the symfony
4
 *              it also has to be updated here.
5
 *
6
 *              This solution was added to avoid for example calling routing api, or having string hardcoded in
7
 *              all the places.
8
 */
9
export default class SymfonyRoutes {
10

          
11
    /**
12
     * @description route used to fetch notes for given category id
13
     */
14
    static readonly ROUTE_NAME_GET_NOTES_FOR_CATEGORY_ID              = "module_notes_get_for_category";
15
    static readonly ROUTE_GET_NOTES_FOR_CATEGORY_ID_PARAM_CATEGORY_ID = "categoryId";



Conclusion

If Symfony is properly configured, and the route file is json instead of yaml/yml then the routes loading will work "out-of-box." However, in my case and as I see in other people's projects the,Annotation is the favorite way to define a route.

Pros

  • Unified routes in frontend and backend.

Cons

  • Necessity to call the command upon adding new routes.
Vue.js Symfony

Published at DZone with permission of Dariusz Włodarczyk. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Mocking Dependencies and AI Is the Next Frontier in Vue.js Testing
  • Serving a Vue.js Application With a Go Backend
  • How To Become a Symfony Certified Engineer: Your Path to Expertise in the Software Industry
  • Build Full-Stack Web App With Firebase, Angular 15, React.js, Vue.js, and Blazor [Video]

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!