How routing internally works in Symfony 4 framework

At the moment of writing this I’m testing the Symfony 4 Framework after reading the following article and also Fabian’s latest posts on Medium.  I’m testing weather the not yet officially released version, will be a future candidate for some new project or not. But the interesting part of this research is that I already realized what I won’t do in new projects. But let’s focus first on the mission of describing how routing works internally in the framework.
So we will go from the Frontend Controller up to the internal guts that say from the route /test let’s execute Controller:test()

http:// bestpractices.local/test

The front-end controller located in /web/index.php bootstraps the framework:

$kernel = new Kernel(getenv('APP_ENV'), getenv('APP_DEBUG'));
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();

As we already know all this framework is based on Request -> Response concept from the beginning to the latest controller action and the Kernel is no exception.  If we open this Kernel we can see that it’s mission is to setup Cache and Logs directories, register the bundles, configure the Container and Routing.

To go deeper in the chain we need to open HttpKernel with the mission described as:
HttpKernel notifies events to convert a Request object to a Response one.
There on the handleRaw method “Handles a request to convert it to a response” is where the whole framework workflow takes place:

namespace Symfony\Component\HttpKernel;

class HttpKernel implements HttpKernelInterface, TerminableInterface {
private function handleRaw(Request $request, $type = self::MASTER_REQUEST)
    {
        $this->requestStack->push($request);
        // request
        $event = new GetResponseEvent($this, $request, $type);
        $this->dispatcher->dispatch(KernelEvents::REQUEST, $event);

  // At this point the routing is already resolved
  // dump($request->attributes);exit();

        if ($event->hasResponse()) {
            return $this->filterResponse($event->getResponse(), $request, $type);
        }

        // load controller
        if (false === $controller = $this->resolver->getController($request)) {
            throw new NotFoundHttpException(sprintf('Unable to find the controller for path "%s". The route is wrongly configured.', $request->getPathInfo()));
        }

// ... Return a response

As we can see on the first lines, the Routing part, is resolved dispatching an Event called KernelEvents::REQUEST

namespace Symfony\Component\HttpKernel\EventListener;

class RouterListener implements EventSubscriberInterface {

public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();

        $this->setCurrentRequest($request);

        if ($request->attributes->has('_controller')) {
            // routing is already done
            return;
        }

        // add attributes based on the request (routing)
        try {
            // matching a request is more powerful than matching a URL path + context, so try that first
            if ($this->matcher instanceof RequestMatcherInterface) {
                $parameters = $this->matcher->matchRequest($request);
                // dump($parameters); // here to see it matched

            } else {
                $parameters = $this->matcher->match($request->getPathInfo());

            }

And in this part of the code we can see that dumping the $parameters the Request attributes are already assigned

$parameters = array(
  "_controller" => "App\Controller\DefaultController::testAction"
  "_route" => "test"
);

Note: Request->attributes is used to store information about the current Request such as the matched route, the controller, etc
But more interesting is to replace this dump for a : dump($this->matcher);
Then we can see that the real matcher of the routing is done by srcDevDebugProjectContainerUrlMatcher since we are currently using DEV as an environment.

This file, that we can find in this path /var/cache/dev/srcDevDebugProjectContainerUrlMatcher.php , is the responsible of returning the request parameters with the right controller to be executed for this route.
Since doing all the routing on the fly will be a real show stopper and we are concerned with performance: reading the configuration from the filesystem may slow down the application.

That’s why there’s a PhpMatcherDumper class which can generate an implementation of UrlMatcherInterface with all configuration in an optimized way.

Even in DEV, this UrlMatcher file, is only rendered again if we update any part of the routing. That’s one of the reasons clearing all cache will make a slow first request.

Lessons learnt from this research are:

  • Keep your routes clean
    Not used / deprecated routes that are still there will make this UrlMatcher unnecessary long and hence slower to resolve.
  • Avoid at all costs using Annotations for the routing
    It’s generally considered a bad practice in OOP and contains much more Cons than Pros
  • Avoid using Assetic
    This generates fully unnecessary routes for every assset in your HTML templates. New versions of Symfony will not come with Assetic so it’s better to get along without it.

I never care to check this routing to the core before and I highly recommend from time to time to check the internals of Symfony. You will learn a lot of the framework essentials and also will be more cautious of how to take the best of it. In my personal case, I learnt much more doing this small research taking your own conclusions, than reading some other developer top 5 list on framework optimization.

The code to reproduce this can be downloaded from public repository:
https://github.com/martinberlin/symfony-flex

Anuncios

Catalunya declared their independence today 27 October 2017

catalunya

About 15.30 the Parlament ha aproved the new Catalán Republic with 70 YES votes and 10 NO votes. What happens next no one knows.

Since I lived in Mallorca for about 12 years I always dreamed to come back to Spain next to where my fathers live in Catalunya, near Arenys de Mar. So now I’m quite worried about what is going to happen next. My wish is that whatever happens next is without violence and represion like in 1-O vote. Violence can never be the answer to anything.

Integrating SSO in a project using Shibboleth authentication

Shibboleth is an open-source identity federation solution that’s used in research and education communities worldwide.

Graphic by ncsu.edu

Basically is a federating agent that consists of 2 components:

1- Service Provider (SP)
 which request attributes, represented in this implementation als storage.luckycloud.de using Apache2-mod-shib 
2- Identity Provider(IDP)
 which broadcasts attributes, and will be implemented in the Login-logic of the site

Now the SP is actually out-of-the-box with apache2 module mod-shib. But my interest here is to do the Identity Provider part als Symfony module.

 

Is someone else out there interested on following the implementation ?

Friction powered Longboard

This is a redesign of the Rotor Flettner project. The effect works after testing it mounted on a windsurf board but it has a potential flaw: Magnus effect has a smaller force than the wind pulling you to the side. The result is that you go more in the wind direction than in the direction that you really want to go. The equivalent to having a very small sail.

But anyways it was a lot of fun to make it and having already the engine and the structure to mount it I thought, why not to try doing something with it :)

And it works, went about 2 kilometers back and forth after discovering I made some design errors and that friction is not my friend. Engineering lessons learnt:
1.- Control cables of the engine should not be touching the floor
2.- Engine should transmit power using some similar material as the wheel
3.- Friction generates heat and 50% of the battery or more is wasted (maybe good for the winter)

Skate and position detail

Wheel coupling with engine

Anderson.Paak dances with us in Berlin

Great concert in Lido with Herr Paak.

Only bad detail: The sound in LIDO. I know that in small shows is almost impossible to have a great acoustic. But I heard Robert Glasper in Festsaal Kreuzberg 2 years ago, and it was just awesome sound. Leaving out the differences, since Festsaal was 90% wood, and thus a great acoustic natural place this time the sound people at Lido did a poor job. Or just the sound system is not prepared for a show like this. Could hear his voice almost always in the background, without a different output channel and always mixed with the bass and the percussion.

Anyways a great performer with a cool band, great DJ and a highly recommendable show. Proud to be dancing with you Brandon!

Learning DOCKER #1

Docker ship with containers

Docker is an exciting technology since April 2013 when it started as open source project. But is only since last year or so that I started hearing more and more about it. And it’s mostly because some companies like Zalando (Berlin) , Spotify and Netflix started implementing it successfully in their servers.

The Docker Mantra is the following :

Build, Ship, Run

Any App, anywhere!

 

I’ve started trying in my Ubuntu 14 machine with this tutorial:

https://docs.docker.com/engine/userguide/dockerizing/

And what I will try to accomplish in the next entries after playing around with it, is to instance some basic WebServer dingie with some simple API, or just Apache+PHP 7+Symfony. Keep tuned!

Some interesting links:
http://docker.com
https://denibertovic.com/talks/supercharge-development-env-using-docker/ Supercharge your environment using Docker (Presentation)

Evolution of the Rotor project

The first prototye of the Flettner Rotor project is constructed with a modified Aluminium Byke structure (Not yet here since needs to be soldiered)

Materials list:

  • Engine Absima with speed control + Battery + Charger
    Forward, Brake and Reverse modus Engine_AbsimaRotor-AkkuAkku_lader
  • Engine Pulley *Riemenscheiberiemenscheiben
  • Industrial bearings *Flanschlager flanschlager5

This is the first sketch and 1:2 drawing

Rotor-drawing

The first material used to build the cilinder, that at the end is not at all a cilinder but a romboid structure.

14493464218191449305646723

Many thanks so far to :
Carlos Fasani, Electronic speed control for the engine
Ing. Mader, Structure advice
Ing. Wawrzyniak, Professional Aluminium welding

Tippgeschwindigkeit Composer (Making it faster)

Nach letzes composer update, ich kriege immer diese Meldung nach update /install : “You are running composer with xdebug enabled. This has a major impact on performance and will break your balls”
So ich habe die richtige Lösung gefunden und wurde mit euch teilen:
$ php -i | xdebug

Guck mal welche config ist schuldig, in meine Ubuntu ist:
/etc/php5/cli/conf-d/20-xdebug.ini

Und einfach comment:
;zend_extension=xdebug.so

Voila! Deine composer is viel schneller ab jetzt. Für mich ist ungefähr 3x schneller.

The evolution of a sponsored Tweet

Mini-post with a tweet advertising test made 5 Nov. 2015 at 13:45.

Budget: 9,20 € ( 10 dollars is the minimun budget )

At the end of the day what it delivered is this:

Impressionen
11.873
696 organisch / 11.177 gesponsert
Interaktionen insgesamt
79 organisch

</div>

Medieninteraktionen 416
Detailerweiterungen 145
Profilklicks 60
„Gefällt mir“-Angaben 8
Retweets 7
Link-Klicks 7
Hashtag-Klicks 2
Folgt 1

I think that it can be a great way to make branding campaigns and to get visibility for a new product or startup.