Blueprint PHP Framework Tutorial – Part 3 (Routing)

Continuing on from bootstrapping the components of the Blueprint PHP Framework, we are going to look at how the router works and how controller methods are invoked. The routing is probably the most crucial part of any framework and it’s no different with this framework. Once the request has been routed to a controller method, you are free to code in any way you like (even procedurally if you’re that way inclined. Yuk!). However, we will see in later posts that there are more powerful ways of managing the response of the application once the request gets to the controller stage.

There are 2 ways to route URLs to controllers:

Default Routing

This form of routing is the most basic and tested before any regex routes. As we did in the last post, to register a namespace in /app/ to use with the application simply do:

Any controllers in that namespace (under /app/{namespace}/controllers/) can now be accessed when a URL matches like so: localhost/test/test/3 will load: /app/{namespace}/controller/Test.php and call:

The controller, action and parameters are determined from the URL once it is exploded by directory separator so test/test/3 is the Test.php controller, testAction() method and the paramater is 3. Clear as mud? good…

Regex routing

The other form of routing is by matching URLs to predefined patterns and determining the controller, action and parameters that way.

Again, as before, to register a route map that uses regex routes do:

By convention it is a good idea to keep your routes file in /app/{namespace}/_routes.php just to be neat.

Your file should look like so:

The regex capture groups (.*) pass the capture as parameters in the controller’s action in the same order they were found.

So if the URL was localhost/test/8-xyz-4 it would match the second regex pattern above test\/(.*)-xyz-(.*). This will load: /app/{namespace}/Controller/Test.php and call:

Routing will always check the namespaces for routes in the order they were loaded, so be aware when you are registering route maps that contain the same controller and action names that only the first one encountered will be invoked.

Just before the method is called, the setContainer() method of the controller is called. This is available in all controllers that extend the default \Blueprint\Controller\Controller class. This special method takes the $app object as it’s only parameter and can be used to pull out the dependencies from the $app object for use in the controller.

Next time we’ll look at how controllers are structured to make the most of the components available…

One thought on “Blueprint PHP Framework Tutorial – Part 3 (Routing)

Leave a Reply