Wildcard Subdomain Prerouting

Standard

Ever have a need to have wildcard subdomains on your CakePHP application? This is the solution to that problem. Assume all subdomains have there own template folder, and the subdomains need to be able to be created and modified on the fly.

Create a subdomain model, as well as a table in your database called Subdomains with the following schema

Initially, the URL is used to extract the subdomain and the host name from the clients entry point. The contents are then assigned to an array in a custom variable using the internal cache. The bootstrap is called within the dispatcher stage of the MVC architecture as shown below.

MVC Structure

CakePHP MVC Structure

Bootstrap.php

The subdomain is now passed through the application and can be accessed by configure::read. A custom library called SubdomainRoute writes values to the cache and the router then reads the results. If a template is set after the SubdomainRoute is initialized it assumes the client is accessing our application on a valid subdomain found in the database.

Routes.php

The subdomain is determined by accessing the mysql subdomain table. The results are stored and later used for routing (above), as well as assigning a template folder for a particular subdomain (below).

app/Lib/Routes/SubdomainRoute.php

The final step is to tell cake which template the subdomain is associated too. This assumes that you have created the templates folder in the directory.

AppController.php