From 09e4229e16cfa174ee83c9217d1d2dbdd19e9b93 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Thu, 30 May 2013 13:33:38 +0200 Subject: [PATCH] [WIP] RESTful routing syntax for UrlManager issue #303 Here is the proposal for RESTful routing syntax: https://gist.github.com/cebe/5674918 --- framework/yii/web/UrlManager.php | 32 ++++++++++++++++++++++++++++- tests/unit/framework/web/UrlManagerTest.php | 2 ++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/framework/yii/web/UrlManager.php b/framework/yii/web/UrlManager.php index 47f5c5d..a6ef0cf 100644 --- a/framework/yii/web/UrlManager.php +++ b/framework/yii/web/UrlManager.php @@ -43,6 +43,28 @@ class UrlManager extends Component * array, one can use the key to represent the pattern and the value the corresponding route. * For example, `'post/' => 'post/view'`. * + * For RESTful routing this shortcut also allows you to specify the [[UrlRule::verb|HTTP verb]] + * the rule should apply for by prepending it to the pattern, separated by a blank. + * For example, `'PUT post/' => 'post/update'`. + * You may specify multiple verbs by separating them with comma + * like this: `'POST,PUT post/index' => 'post/create'`. + * Note that [[UrlRule::mode|mode]] will be set to PARSING_ONLY when specifying verb in this way + * so you normally would not specify a verb for normal GET request. + * + * Here is an example configuration for RESTful CRUD controller: + * ~~~php + * array( + * 'dashboard' => 'site/index', + * + * 'POST s' => '/create', + * 's' => '/index', + * + * 'PUT /' => '/update', + * 'DELETE /' => '/delete', + * '/' => '/view', + * ); + * ~~~ + * * Note that if you modify this property after the UrlManager object is created, make sure * you populate the array with rule objects instead of rule configurations. */ @@ -115,9 +137,17 @@ class UrlManager extends Component foreach ($this->rules as $key => $rule) { if (!is_array($rule)) { $rule = array( - 'pattern' => $key, 'route' => $rule, ); + if (($pos = strpos($key, ' ')) !== false) { + $verbs = substr($key, 0, $pos); + if (preg_match('/^((GET|POST|PUT|DELETE),?)*$/', $verbs, $matches)) { + $rule['verb'] = explode(',', $verbs); + $rule['mode'] = UrlRule::PARSING_ONLY; + $key = substr($key, $pos + 1); + } + } + $rule['pattern'] = $key; } $rules[] = Yii::createObject(array_merge($this->ruleConfig, $rule)); } diff --git a/tests/unit/framework/web/UrlManagerTest.php b/tests/unit/framework/web/UrlManagerTest.php index 0f08790..d0e8775 100644 --- a/tests/unit/framework/web/UrlManagerTest.php +++ b/tests/unit/framework/web/UrlManagerTest.php @@ -248,4 +248,6 @@ class UrlManagerTest extends TestCase $result = $manager->parseRequest($request); $this->assertFalse($result); } + + // TODO test RESTful pattern syntax e.g. 'GET index' => 'site/index' }