PHPackages                             eberfreitas/cakephp-power-router - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. eberfreitas/cakephp-power-router

AbandonedArchivedCakephp-plugin[Framework](/categories/framework)

eberfreitas/cakephp-power-router
================================

Juicy new features for your cake's routing stuff

0.1.1(10y ago)113801[1 issues](https://github.com/eberfreitas/cakephp-power-router/issues)MITPHP

Since Dec 14Pushed 10y ago1 watchersCompare

[ Source](https://github.com/eberfreitas/cakephp-power-router)[ Packagist](https://packagist.org/packages/eberfreitas/cakephp-power-router)[ Docs](http://github.com/eberfreitas/cakephp-power-router)[ RSS](/packages/eberfreitas-cakephp-power-router/feed)WikiDiscussions master Synced today

READMEChangelog (2)Dependencies (1)Versions (2)Used By (0)

PowerRouter Plugin
==================

[](#powerrouter-plugin)

[![Build Status](https://camo.githubusercontent.com/7a78f16b94a1eb0cbd489fa9bb271de8b81a39378e007d3b44b48a4ea8017fda/68747470733a2f2f7472617669732d63692e6f72672f65626572667265697461732f63616b657068702d706f7765722d726f757465722e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/eberfreitas/cakephp-power-router) [![Coverage Status](https://camo.githubusercontent.com/eca33fad266a79f5756a5655b831938926bacf4e2f7ae73b47a99beb98f5b476/68747470733a2f2f696d672e736869656c64732e696f2f636f766572616c6c732f65626572667265697461732f63616b657068702d706f7765722d726f757465722e737667)](https://coveralls.io/r/eberfreitas/cakephp-power-router?branch=master)

PowerRouter is a plugin that extends how your default Router can be used. It enables three new features:

- Add named routes
- Manipulate the params from a matched route
- Matches a route only if it conforms to a given condition

Requirements
------------

[](#requirements)

- CakePHP 2.x (tested on 2.4 and 2.5 but should work on every 2.x release)
- PHP 5.3 or later (should work on 5.2 but it is not tested)

Installation
------------

[](#installation)

**Using [Composer](http://getcomposer.org/)**

Add the plugin to your project's `composer.json` - something like this:

```
{
    "require": {
        "eberfreitas/cakephp-power-router": "dev-master"
    }
}
```

Because this plugin has the type `cakephp-plugin` set in it's own `composer.json`, composer knows to install it inside your `/Plugins` directory, rather than in the usual vendors file. It is recommended that you add `/Plugins/PowerRouter` to your .gitignore file. Why? [read this](http://getcomposer.org/doc/faqs/should-i-commit-the-dependencies-in-my-vendor-directory.md).

**Manual**

- Download this:
- Unzip that download
- Copy the resulting folder to app/Plugins
- Rename the folder you just copied to `PowerRouter`

**GIT Submodule**

In your app directory type:

```
git submodule add git://github.com/eberfreitas/cakephp-power-router.git plugins/PowerRouter
git submodule init
git submodule update
```

**GIT Clone**

In your plugin directory type:

```
git clone git://github.com/eberfreitas/cakephp-power-router.git PowerRouter
```

Usage
-----

[](#usage)

PowerRouter is a custom route class that extends on the CakeRoute. This way you can use it to define your routes and take advantage of it's features. Using it will replace both `match` and `parse` methods.

The `match` method is used to handle reverse routing and `parse` is used to parse requests. You can read more about custom route classes on the [CakePHP book](http://book.cakephp.org/2.0/en/development/routing.html).

In order to use the features from PowerRouter, first you need to load the plugin adding the following line in your `app/Config/bootstrap.php`:

```
CakePlugin::load('PowerRouter');
```

Later, import the library into your "app/Config/routes.php" file like this:

```
App::uses('PowerRoute', 'PowerRouter.Lib');
```

After that you can start to define your routes like this:

```
Router::connect(
    '/path',
    array('controller' => 'pages', 'action' => 'view'),
    array(
        'routeClass' => 'PowerRoute',
        'routeName' => 'main-path',
        'callback' => $callback,
        'condition' => $condition
    )
);
```

But, if you are planning on using PowerRoute a lot, you can use the helper class `PowerRouter` in order to make declaring new routes a little bit easier. In that case, instead of importing the 'PowerRoute' lib, import the 'PowerRouter' lib like this (mind the "r"):

```
App::uses('PowerRouter', 'PowerRouter.Lib');
```

Now you can do something like this:

```
PowerRouter::connect(
    'main-path',
    '/path'
    array('controller' => 'pages', 'action' => 'view'),
    array(
        'callback' => $callback,
        'condition' => $condition
    )
);
```

Here is how the `PowerRouter::connect` method is described:

```
PowerRouter::connect($name, $route, $defaults = array(), $options = array()) { /*...*/ }
```

Where:

- `$name` is the name you want to give to this route. Ideally it should be a unique identifier
- `$route` is your route path, something like `/:controller/:action/:id` and so on, just like in regular routes
- `$defaults` is an array describing the default route parameters, just like in regular routes
- `$options` works just like the options param from regular routes as well. Here you can also declare two new keys: `condition` and `callback`. We will take a look at those pretty soon.

### Using named routes

[](#using-named-routes)

So, the first thing you can do with PowerRouter is to define named routes. This will make it easier and faster to match routes when doing any kind of route matching. Let's see an example:

```
PowerRouter::connect(
    'about',
    '/about-us',
    array('controller' => 'pages', 'action' => 'display', 'about')
);
```

Now, if you want to link to this page on your views, you can do something like this:

```
echo $this->Html->link('About us', array('routeName' => 'about'));
```

That will match the right route. You can also combine params:

```
// In your routes.php

PowerRouter::connect(
    'product-view',
    '/product/:slug/:id',
    array('controller' => 'products', 'action' => 'view')
);

// In your views

echo $this->Html->link(
    $product['Product']['title'],
    array(
        'routeName' => 'product-view',
        'slug' => $product['Product']['slug'],
        'id' => $product['Product']['id']
    )
);
```

### Using callbacks

[](#using-callbacks)

With callbacks you can manipulate your route's params before it is used by the application. When a route is parsed it returns an array with the params it will use such as the controller that was matched, the action, among other things. Using a callback you can inject or modify information into that array. The callback can be anything that `is_callable`, including closures. Let's take a look at an example:

```
// routes.php

$transformRoute = function ($params) {
    $params['action'] = 'dash_' . $params['action'];

    return $params;
};

PowerRouter::connect(
    'route',
    '/dashboard/:controller/:action/*',
    array(),
    array('callback' => $transformRoute)
);
```

Now, when someone hits `/dashboard/user/view/123` you will "redirect" the request to the `UserController::dash_view` method. The callback is executed and effectively changes the params being used on that request.

It's really important that you return the `$params` variable at the end of the callback function, as that will be used by the application from now on.

### Using conditional callbacks

[](#using-conditional-callbacks)

Another form of callback that PowerRouter enables is the `condition` one. With that callback you can block a route from being used by any conditions you define in that callback. The function should return a boolean value representing the validity of that route. Example:

```
$condition = function () {
    return Configure::read('route') === true;
};

$routes = PowerRouter::connect(
    'test',
    '/findamatch',
    array(
        'controller' => 'main',
        'action' => 'view'
    ), array(
        'condition' => $condition
    )
);
```

Depending on the value of the `route` configuration key, the `test` route will be used or not. With that you can dynamically mold your routes to respond according to a given environment or set of conditions.

Alternatively you can pass an array of callback functions that will be executed in order until any of the them deny access to that route.

License
=======

[](#license)

The MIT License (MIT)

Copyright (c) 2014 Éber Freitas Dias

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity20

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

3799d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/0557f6ff4744c469038454c1953e93cdb2aeb3e207f747380e6f895df9fa7729?d=identicon)[eberfreitas](/maintainers/eberfreitas)

---

Top Contributors

[![eberfreitas](https://avatars.githubusercontent.com/u/137487?v=4)](https://github.com/eberfreitas "eberfreitas (11 commits)")

---

Tags

pluginroutercakephproutingroute

### Embed Badge

![Health badge](/badges/eberfreitas-cakephp-power-router/health.svg)

```
[![Health](https://phpackages.com/badges/eberfreitas-cakephp-power-router/health.svg)](https://phpackages.com/packages/eberfreitas-cakephp-power-router)
```

###  Alternatives

[pecee/simple-router

Simple, fast PHP router that is easy to get integrated and in almost any project. Heavily inspired by the Laravel router.

696214.6k17](/packages/pecee-simple-router)[izniburak/router

simple router class for php

23522.6k7](/packages/izniburak-router)[heropoo/routing

A simple and fast route. Use tree structure storage, fast matching!

115.6k1](/packages/heropoo-routing)[ecoal95/php-router

Minimal routing library

271.0k1](/packages/ecoal95-php-router)[developermarius/simple-router

Simple, fast PHP router that is easy to get integrated and in almost any project. Heavily inspired by the Laravel router.

112.4k](/packages/developermarius-simple-router)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
