Skip to content

Instantly share code, notes, and snippets.

@TamiasSibiricus
Created December 13, 2014 13:42
Show Gist options
  • Save TamiasSibiricus/61e2e566d16847ee5a2f to your computer and use it in GitHub Desktop.
Save TamiasSibiricus/61e2e566d16847ee5a2f to your computer and use it in GitHub Desktop.
<?php
/*
* Routing sample
* Router::scope('/', function ($routes) {
* $routes->fallbacks('InflectedRoute');
* });
* Router::connect(
* '/:slug',
* ['controller' => 'Articles', 'action' => 'view'],
* ['routeClass' => 'SlugRoute']
* );
*
* Here is bypass filter for short slug routes
*/
namespace App\Routing\Filter;
use Cake\Event\Event;
use Cake\Routing\DispatcherFilter;
use Cake\Routing\Router;
use Cake\ORM\TableRegistry;
class SlugRoutingFilter extends DispatcherFilter {
//Runs after main Routing filter
protected $_priority = 11;
public function beforeDispatch(Event $event) {
$request = $event->data['request'];
//Loading Articles table and set query
$query = TableRegistry::get('Articles')->find('all')
->where(['Articles.slug LIKE' => $request->params['controller']]);
// Check for article with slug
if($query->count()){
// override params in request if article exists
$request->params['pass']['slug'] = $request->params['controller'];
$request->params['controller'] = 'Articles';
$request->params['action'] = 'view';
Router::setRequestInfo($request);
}
}
}
@davidcm86
Copy link

Hi!
How can I use it?
In my bootstrap a did:
DispatcherFactory::add('SlugRouting', ['for' => '/:slug']);

And in my routes:
Router::connect('/:slug', ['controller' => 'Articles', 'action' => 'articulo']);

I put your filter in src/Routinb/Filter, but cakephp seid me: controller not found....

Im crazy with sort slug route...

Can you help me?

Thank you!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment