Routes

In CodKep, a location is the unique end portion part of the URL for a specific function or piece of content. For instance, for a page whose full URL is http://example.com/?q=node/7, the location is node/7. If your site is using clean URLs, the full URL in this example would be http://example.com/node/7 the path would still be node/7. Also URL aliases can completely replace what visitors see as the URL, so the locations discussed here are sometimes called internal URLs or internal paths.

Locations are important because many configuration screens or admin area refer to them. Here are some examples of locations you might find in a CodKep site:

The URL you find could have several forms:

 http://example.com/index.php?q=[something]
  or
 http://example.com/?q=[something]

In this case, the [something] after ?q= is the location. For example, if the URL is http://example.com/?q=node/7, the route is node/7. Under the hood the index.php of the CodKep will receive this node/7 location and do a routing process to find the corresponding page to display.

 http://example.com/[something]
  or
 //In case the CodKep installed in a subdirectory of the web server
 http://example.com/[your CodKep subdirectory]/[something]

In this case, the [something] after the base path of your site is the location. For example, your URL could be http://example.com/node/7 or http://example.com/mysubdir/node/7 the location in either case is node/7. In case you install CodKep in a subdirectory (like the second case) the $site_config->base_path variable should set in site settings to that subdirectory where the CodKep installed.

Add custom locations

We can use HOOK_defineroute hook to add our own routes to the CodKep.

An implementation HOOK_defineroute hook have to return an array of associated arrays which define the routes and the actions matched to that routes. This hook does not have any parameter.

For instance mymodule wants to add the "ownpage" route to the codkep with a callback function:

<?php
//mymodule.php file

function hook_mymodule_defineroute()
{
    $r = [];
    $r[] = [
             'path' => 'own',
             'callback' => 'ownpage',
           ];
    return $r;
}

function ownpage()
{
    return 'This is my first page!';
}

When mymodule.php is enabled in _modules.php the page is should alive on url:

In case the $site_config->base_path value is "testsite"

The route definition array

The route definition array is an element should return by HOOK_defineroute hook

Parameters in URL

You can receive parameters passed in URL.
In case you want to receive a parameter in URL you have to put a placeholder to the path string of the route. The placeholder should be the desired variable name between {} sings.

Let's see some example routes with parameters

The parameters defined through route paths are accessible by par($parameter_name) function, but disabled by default because security reasons. Read parameters chapter to learn how to use it.

Caching routes

The CodKep caches the results of HOOK_defineroute hook calls if APC is available and enable in the webserver. It means that after you create a new HOOK_defineroute hook or change the content of one you have to clear the caches to make it work. You can drop the current cahches by hit the following CodKep internal url:

Note: The APC is an optional requirement of CodKep. If it is not available the system work properly but a bit slower.

Note2: In case you create a defineroute hook which generate dynamic results (like page module) you should take care of dropping route caches if the dynamic content possibly changed. You can do this by calling ccache_delete('routecache') code.

Generating URLs

Because the internal location are not real urls the programmer should use a special functions to generate web urls correctly unified way.

Strongly recommend to use url generator functions of CodKep both internal locations and outer urls too!

Generation of an url in codkep:
url($loc, array $query = array(), array $options = array())

The function returns a printable url which can directly used in browsers.

print "The url of the user login is: ".url("user/login");
print "The site of the author is: ".url("http://hyperprog.com");
//This is not a link, just put the raw url.
//To make link use l() instead of url()

The output of the code above could be:

The url of the user login is: http://example.com/index.php?q=user/login
The site of the author is: http://hyperprog.com

The url() function can invoke some hook during the url generation. This hooks receives the url object parameter, which contains the parts of the url, and may be modified. (Use d2() debugging function to determine the structure of $uo)

Generating Links

Many cases we have to generate html links instead of simple urls. The CodKep have a html anchor tag generator function, which uses the url() function to generate a formatted html link.

l($text, $loc, array $options = array(), array $query = array(), $fragment = NULL)

The function returns a printable link/anchor tag which can directly used in browsers.

print l("Login","user/login");
print l("The site of the author","http://hyperprog.com",["class" => "extlink"]);
print l("Edit content: $title","edit/$id",[],['foo' => 'full']);

The code above will generate the following html content (It may be different according to the settings of site)

<a href="index.php?q=user/login">Login</a>
<a href="http://hyperprog.com" class="extlink">The site of the author</a>
<a href="index.php?q=edit/34&foo=full">Edit content: second</a>

Redirections

In case the browser open a CodKep page, some location is requested. After the routing process is finished the programmer always can query the actual location is requested by the current_loc() function.

current_loc() - Returns the current location path if available.


It is possible to change the location is currently executed. There is two possible way to do this:

load_loc($location, ...parameters...)

Stops (or won't start) the current executing, drops the outputs, and immediately start execution of the parameter passed location/page. It means that this function does internal routing again, so the requested url in the browser will be unfinished.

Note: Because this function do internal redirection the original requested url is stay unchanged in browser. After this kind of redirection the client cannot detect the redirection. It will know that it see the requested url, but the content will change.

goto_loc($location)

Stops (or won't start) the current executing, drops the outputs, and immediately send redirection headers to the browsers with the parameter passed location. This function does redirection with http redirect header.

Note: Bacause this function requiest the redirection from browser, the url will change in the browser's address line.

Tags

It is possible to associate tags to the route definition array. This tags should starts with # sings and continue with a string. This string will be the name of the tag. The value of the tag will be the value of the array item which can be a simple string.

This code defines two tag (mainmenu and public) in a HOOK_defineroute hook:

<?php
function hook_mymodule_defineroute()
{
    $r = [];
    $r[] = [
             'path' => 'own',
             'callback' => 'ownpage',
             '#mainmenu' => 'My own page',
             '#public' => 'My own page',
           ];
    $r[] = [
             'path' => 'secondsample',
             'callback' => 'mysecondpage',
             '#mainmenu' => 'My second page',
           ];
    return $r;
}

Note: This tags does not have special meanings. This is just arbitrary strings begins with # sign.

Later we can use this tags to get special array of routes by routes_tag_array() function.

routes_tag_array($tag)

This function returns an associated array of routes where:

In the example above the result of routes_tag_array("mainmenu"); is:

[
 "My own page" => "own",
 "My second page" => "secondsample"
]

This function helps to use array of routes for a different purposes like menu building or link collections etc...

The mainmenu has a special meaning. It can used to place a location to the main menu. See menu part of theme documentation.

Clean URLs

Like the Drupal CMS the CodKep also can use "Clean URLs" to looks internal urls better:
By default, the generated URLs for your site's pages that look like http://www.example.com/?q=node/83. With so-called clean URLs this would be displayed without the ?q= as http://www.example.com/node/83.

The style of URLs using ?q= can be hard to read, and may even prevent some search engines from indexing all the pages of your site.

Prerequisites of using Clean urls:

To use clean urls have to set the webserver to redirect all queries to index.php of CodKep.
Note: The index.php of CodKep can receive the original query string and it can interpret as normal queries.

Sample configs for webservers to use clean urls:

# nginx config
server {
    listen 80;
    listen [::]:80;
    server_name sandbox.example.com;
    root /var/www/mypage;
    index index.php;
    location / {
        try_files $uri @rewrite;
    }
    location @rewrite {
        rewrite ^ /index.php;
    }
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
    }
}
# apache2 config
#
# Have to enable rewrite module:
#  a2enmod rewrite
#
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName sandbox.example.com
    DocumentRoot /var/www/mypage
    <Directory /var/www/mypage/>
        Options -Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
        RewriteEngine on
        RewriteBase /
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ index.php [L]
    </Directory>
    ErrorLog ${APACHE_LOG_DIR}/error.log
    LogLevel warn
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

On apache2 it is possible to do this redirection from htaccess file

DirectoryIndex index.php
Options -Indexes
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L]

Enable clean urls:

In case the webserver are correctly set the only thing to do is enable clean urls in CodKep settings:

// _settings.php
global $site_config;
// ...
$site_config->clean_urls = true;

If the clean_urls variable is set the url() and l() functions are also generate clean urls.

Hooks related to routes

The following hooks can be implemented related to routes.

HookDescription
HOOK_defineroute()Define routes in the system
HOOK_outbound_internal_url($url_object)It can modify the generated url which targets an internal location of the site
HOOK_outbound_internal_file_url($url_object)It can modify the generated url which targets an internal location of the site but not known by routing (probably a file url)
HOOK_outbound_external_url($url_object)It can modify the generated url which targets out of the site
HOOK_inbound_url($iu_object)It runs immediately before the routing process. It can do a permanent redirection or url aliases
Page generated in 0.0147 seconds.