Routing and urlManager problem


(xNicox) #1

Hi, I’m an old user of YII 1.1, with excelent results.

Now I’m trying 2.0, and I want to create a RESTFull api with Yii 2.0.

I downloaded and installed yii2, the I create a model and a controller with two of my tables.
But I’m facing a real problem,
When I activate urlManager and set ‘enablePrettyUrl’ => true,
i can’t acced site/index and i can’t access my controllers.

because urlManager is global… I can’t have the web app running with the standar URL format and some routes to be accesed with some rules for the REST apis ?

Why I loose site/index ??

Best Regards


(Wilson) #2

You should apply some rules for enabling pretty Url.

'urlManager' => [
            'class' => 'yii\web\UrlManager',
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
                ''=>'site/index',
                '<action:(index|login|logout)>'=>'site/<action>',
                '<controller:\w+>/<id:\d+>' => '<controller>/view',
                '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
                '<controller:\w+>/<action:\w+>' => '<controller>/<action>'
            ],
        ],

and do not forget to edit .htaccess file if you’re using apache as your web server.

RewriteEngine on
 
# If a directory or a file exists, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward the request to index.php
RewriteRule . index.php

(xNicox) #3

Great! It work now as a web ! But I get to this problem when I try to test RESTFull api.

Suposse I have a WebApp and now I want to expose son entities as a REST service.
How can I achieve that ?

Best Regards

PS: Maybe is a good idea to put that info in the RESTFull item of the DOCs.


(xNicox) #4

ok,

I found a way, I created another Controller.

namespace app\controllers;
use yii\rest\ActiveController;
class Cliente_apiController extends ActiveController

{
   public $modelClass = 'app\models\Cliente';

}

in web.php i added this line un urlManager:

...

'<controller:[\w-]+>s' => '<controller>/index',
        ['class' => 'yii\rest\UrlRule', 'controller' => 'cliente_api'],
...

so when I point url in browser to:
http://localhost/basic/web/cliente_apis

I guet a beatiful json with data…

and with : http://localhost/basic/web/cliente_api/2

I get data of one record …
My goal is to map the url like : /api/cliente/list

and route “cliente” to Cliente_api controller…

Best Regards.

PS: This what I try to achieve.
https://www.yiiframework.com/wiki/175/how-to-create-a-rest-api


(Wilson) #5

I’m glad you has solved the problem. I’m not experience with API.