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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
Partner Zones AWS Cloud
by AWS Developer Relations
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
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Frameworks
  4. The Wheel: Symfony Routing

The Wheel: Symfony Routing

Giorgio Sironi user avatar by
Giorgio Sironi
·
Jul. 01, 13 · Interview
Like (0)
Save
Tweet
Share
5.02K Views

Join the DZone community and get the full member experience.

Join For Free

Once I started retrofitting a Request object over PHP 4 code, and transforming PHP scripts into objects, a natural need was to associate URLs with the object going to answer a request to them.

You can do this with a simple map:

  '/foo' => 'MyPackage\Foo',
  '/bar' => 'MyPackage\Bar',
  ...

but as you scale to many routes of different kinds you may need to introduce additionalo logic on your simple array. The simplest example that calls for a structured solution is that of dynamic routes such as /purchase/42, or even of routing subdomains such as mail.example.com and good.example.com.

Fortunately, there are already open source solutions that address the problem such as Symfony Routing .

Example code

Suppose $routesToClasses is an array like the one in the top of the article:

[
  '/foo' => 'MyPackage\Foo',
  '/bar' => 'MyPackage\Bar',
]

To match URLs requested by the client, I have adapter this code straight from documentation in a few minutes:

$routes = new RouteCollection();
foreach ($this->routesToClasses as $routePath => $class) {
  $route = new Route($routePath, array('class' => $class));
  $routes->add($routePath, $route);
}

$route = rtrim($selectedRoute, '/');
$context = new RequestContext($selectedRoute);
$matcher = new UrlMatcher($this->routes, $context);

try {
  $parameters = $matcher->match($selectedRoute);
  return $parameters;
} catch (ResourceNotFoundException $e) {
  // 404
}

where $selectedRoute is taken from the Request object or from $_SERVER (in my case REDIRECT_URL, but other keys may apply).

In $parameters, the result of the matching, you find the 'class' key added during initialization, plus any other parameter passed in the same argument to Route. It is also easy enough to provide dynamic URLs, whose variable values are provided as additional parameters:

$route = new Route("/purchase/{id}", array('class' => 'PurchaseController'));
// $parameters will contain not only 'class' but also 'id'

Furthermore, Symfony Routing adds an implicit '_route' key to the matched parameters, containing the $routePath with which the Route was added to the configuration. It is common to rely on this variable to integrate the selection with the rest of an application, for example using the paths as keys in other configuration maps (hidden inside objects).

Cohesion

I appreciate the Routing's job is to associate an URL template to a set of parameters declared by you, enriching them with dynamic (and on occasion implicit such as _route) ones.

It's then your job to decide how to transform this result: parameters can be strings but also controllers, objects in general, or closures that create them for lazy-loading. In my case, the 'class' parameter may be a string that is instantiated via reflection or a closure.

Some of the things Symfony Routing does not do:

  • messing with your Request object and modifying its state, being it the Symfony\HttpFoundation one or your own class.
  • introducing additional dependencies: while there are some suggested installations such as Symfony Config and Symfony Yaml, they are by no means necessary.
  • introducing megabytes of code for a single functionality: we are talking of 70-80 classes, half of which are tests installed through Composer together with the production code.
  • scattering files in dozens of namespaces. All classes are inside the Symfony\Component\Routing namespace and as such even the repository has a good, not Java-like feeling (main/src/org/example/com/routing/Route.java).
  • imposing PHP upgrades: the dependency on PHP 5.3.3 is the bare minimum now that 5.5 is out.

Conclusion

In short, routing is not always a simple job, and can grow complex with the size of your application. It is however a self-contained task that a library can accomplish without taking root all over your application: I wrapped Symfony Routing into a single SymfonyAdapterSet class, implementing a common interface AdapterSet which returns the built object given a URL.

I definitely recommend outsourcing some of the responsibilities of your PHP application to Symfony Routing with respect to doing the matching yourself, with the exception of fixed URLs. What called for the inclusion of the library in the last application I worked on was the need for dynamic ones.

Symfony

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • 10 Things to Know When Using SHACL With GraphDB
  • Host Hack Attempt Detection Using ELK
  • Introduction To OpenSSH
  • [DZone Survey] Share Your Expertise and Take our 2023 Web, Mobile, and Low-Code Apps Survey

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: