I have been setting up REST on Yii2 for two days already, and due to different issues and lack of details in documentation I haven't reach my goals yet.
For now I need to make pluralize working for my controller. I can get all users by requesting GET to my
virtualhost/user,
but 404 for:
virtualhost/users,
virtualhost/user/1,
virtualhost/users/1.
I have UserController.php made by (official documentation):
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'app\models\User';
}
I have autogenerated model User, and I have rules, almost the same as in the same quick official guide:
...
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => false,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'User'],
],
]
....
I have tried to set pluralize property to true, I even checked, does my yii\rest\UrlRule working at all - seems it does not, var_dumps in its init() shows nothing.
I would appreciate any help.
I have found the answer. The problem was in controller naming. It is called User, but should be mentioned in rules like 'user', lowercase. I don't know why does developers haven't added any warnings or errors on that thing.
Related
I have a noob question, but googling for several hours didn't get me closer to the answer.
I want that when I enter the following url into my browser, that is gets assigned to a specific controller action.
Imagine I have the following url:
http://localhost:5555/tractor-unit/?param1=1¶m2=abc
How should the rules looks like to process this request in a certain action in a certain controller.
What I've tried so far:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'tractor-unit/?param1=<param1:\d+>¶m2=<param2:\w+>' => 'tractor/do'
]
],
That doesn't work. I just don't understand how the rules entry should be written in order to pass this request to a controller named tractor and its action do. Or maybe I totally misunderstood the whole url manager concept.
simple add to action "do" in tractor-unit controller next:
public function actionDo($param1=null, $param2 = null)
if this don't work
remove section "rules" from config
I'm facing a problem where I've configured RBAC in Yii 2.0 but it does not work - meaning it dooes not prevent any of the pages from being loaded - even as guest.
This is in my web.php config (also in my console.php):
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
The migrations have completed successfully.
This is how behaviors() look like at the moment, but I tried many different ways.
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['error'],
'allow' => true,
//'roles' => ["?"],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
If I implement the behaviors() function in my controller, the framework starts doing some access-handling, but the goal of using a DB as I understand should be that the RBAC system takes over this responsibility - meaning I don't have to enable/disable every single action I write for every single role.
I have added a Role "Admin" and assigned a few of the available routes (actions) to it.
Then I assigned this role to my User name. In theory this should enable my login to access those specific routes but nothing else - instead, I can traverse the site however I please, no 403s whatsoever. (This is why I'm saying RBAC acts like it's non-existing.)
Any hints or tips are appreciated.
Thanks.
where is your authManager configuration located?
According to [yii2 guide]
If you are using yii2-basic-app template, there is a config/console.php configuration file where the authManager needs to be declared additionally to config/web.php. In case of yii2-advanced-app the authManager should be declared only once in common/config/main.php.
Update to this question, I just tried do rbac manually
My result
We must do conditional in every action like
...
public function actionAbout()
{
if (Yii::$app->user->can('ViewAbout')) {
echo "you may see view about";
} else {
echo "view about is prohibited";
}
// return $this->render('about');
}
...
If you want assign it in common way, you better use extension/module that handle authmanager (like yii2-admin, yii2-mimin, etc)
Hope this answer help
My Folder and code strucure is -
api/
modules/
v1/
controllers/
UserController.php
BaseController.php
Module.php
v2/
controllers/
UserController.php
BaseController.php
Module.php
And my application configuration would look like:
'modules' => [
'v1' => [
'basePath' => '#app/modules/v1',
'class' => 'api\modules\v1\Module'
],
'v2' => [
'basePath' => '#app/modules/v2',
'class' => 'api\modules\v2\Module'
],
],
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => false,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => ['v2/user']],
['class' => 'yii\rest\UrlRule', 'controller' => ['v1/user']],
],
]
I am following the same procedue as given on yii2 doc But its versioning not working .
UPDATE :
I have created a costume rule and parse according that . Looking for something else .
class ApiUrlRule implements UrlRuleInterface {
public function parseRequest($manager, $request) {
$pathInfo = $request->getPathInfo();
$paramas=$request->getQueryParams();
$version=Yii::$app->response->acceptParams['version'];
$route = Yii::$app->response->acceptParams['version'].'/'.$pathInfo;
return [$route,$paramas];
}
public function createUrl($manager, $route, $params) {
}
}
From the docs you linked:
Both methods have their pros and cons, and there are a lot of debates about each approach. Below you'll see a practical strategy for API versioning that is a mix of these two methods:
Put each major version of API implementation in a separate module whose ID is the major version number (e.g. v1, v2). Naturally, the API URLs will contain major version numbers.
Within each major version (and thus within the corresponding module), use the Accept HTTP request header to determine the minor version number and write conditional code to respond to the minor versions accordingly.
The major api version number is determined by the url, as you've set in your urlManager. You can access them by calling your-yii2-app.com/v1/controller/action or your-yii2-app.com/v2/controller/action. Any code that parses the header must be written by you:
Accept HTTP request header to determine the minor version number and write conditional code to respond to the minor versions accordingly.
If you want to write a custom api version header functionallity, this is possible. I suggest you try and create a new question if you run into trouble.
I have an old website, now I have written it with new version of yii framework and I want change the urls, but because of SEO problems I want to keep my old urls.
Now when the user enters www.mysite.pre/car/details/10908 I want application renders www.mysite.pre/site/show_detail/10908 how could I handle it in yii2 Routing?
Assuming you have got this action in your SiteController class
public function actionShow_detail($id) {}
Add this in your configuration file:
// ...
'components' => [
// ...
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
// ...
'car/details/<id:\d+>' => 'site/show_detail',
],
],
],
More details and information about Yii 2 routing can be found in "Routing and URL Creation" section of The Definitive Guide to Yii 2.0.
I am building my website with Yii2 advanced template. The URL is rewritten into
localhost:9001/projectyii/page/index/#/demo
(page is controller, index is action, /#/demo is just a route for AngularJS on frontend)
Everything works fine on my localhost. When I upload it into my server, whenever if I hit the URL has prefix example.com/projectyii/, it will throw the following exception
ReflectionException
Class yii\web\urlManager does not exist
1. in /home/scott/public_html/projectyii/vendor/yiisoft/yii2/di/Container.php at line 415
406407408409410411412413414415416417418419420421422423424 * #return array the dependencies of the specified class.
*/
protected function getDependencies($class)
{
if (isset($this->_reflections[$class])) {
return [$this->_reflections[$class], $this->_dependencies[$class]];
}
$dependencies = [];
$reflection = new ReflectionClass($class); // error here
I notice that there are some other websites that have been running on same server already (they are all using Yii 1.1.13) and they have been working without problem, such as
example.com/project1/
example.com/project2/
...
it's just failed just this new site in Yii2.
The setting is under of components on /frontend/config/main.php is
'urlManager' => [
'class' => 'yii\web\urlManager',
'baseUrl' => $baseUrl,
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [],
]
The error told that it could not find the urlManager class, but the class does exist, the namespace is fine because I DO NOT modify anything on the vendors folder where contains that urlManager class.
I do not understand what I am missing here. Any help is appreciated! Thanks
Linux like other unix systems are case sensitive you should use:
'class' => 'yii\web\UrlManager', instead of urlManager