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.
Related
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
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.
Right now I'm trying to implement themming for my Yii2 based project.
How I see the thing now:
User chooses an application theme from the list on the settings
page in backend.
Using yii2-settings I'm saving all the
configuration data in DB (pretty easy).
In the application
bootstrap.php I'm creating new alias called #theme. Basically it
should lead us to a application theme base path (used in search
paths, assets manager, e.t.c.).
According to official
documentation, that's how I configured my view component:
'view' => [
'theme' => [
'basePath' => '#theme',
'baseUrl' => '#theme',
'pathMap' => [
'#app/views' => '#theme',
'#app/widgets' => '#theme/widgets',
'#app/modules' => '#theme/modules',
],
],
],
An issue I have is with p.3. According to yii2-settings documentation that's how I supposed to read the settings:
$theme = Yii::$app->settings->get('name', 'general');
Yii::setAlias('#theme', realpath(dirname(__FILE__)."/../../themes/$theme"));
But obviously, it's not working for me because of yii2-settings component didn't initialized yet when bootstrap.php is called. I've been trying to initialize it later in the init() method of my base controller, then adjust other aliases manually, but I feel that way being somewhat 'unclean', and also it still fails because of #theme alias is also used in asset file which is Yii2 starting to publish before calling the controller's init method.
So does anyone has any thoughts of how to do that 'hacking' the code as less as possible? I know I could just move configuration to some file, then read it manually before the application initialization, but it's still not the way I want to go.
Maybe there's some way to override some system component to set the alias after db component is loaded, but before view component configuration? Or Yii loads this components in a different order? Anyway. Any help would be appreciated!
You could try an Application Event in bootstrap:
\Yii::$app->on(\yii\base\Application::EVENT_BEFORE_REQUEST, function ($event) {
$theme = Yii::$app->settings->get('name', 'general');
Yii::setAlias('#theme', realpath(dirname(__FILE__)."/../../themes/$theme"));
});
OR in configuration file:
[
'on beforeRequest' => function ($event) {
// ...
},
]
From Yii 2 docs:
EVENT_BEFORE_REQUEST This event is triggered before an application
handles a request. The actual event name is beforeRequest.
When this event is triggered, the application instance has been
configured and initialized. So it is a good place to insert your
custom code via the event mechanism to intercept the request handling
process. For example, in the event handler, you may dynamically set
the yii\base\Application::$language property based on some parameters.
Here's the final solution:
config/bootstrap.php:
// Setting a temporary path for components configuration - will be changed later
Yii::setAlias('#theme', realpath(dirname(__FILE__)."/../../themes/"));
config/main.php
'components' => [
'view' => [
'theme' => [
'basePath' => '#theme',
'baseUrl' => '#theme',
'pathMap' => [
'#app/views' => '#theme',
'#app/widgets' => '#theme/widgets',
'#app/modules' => '#theme/modules',
],
],
],
],
'on beforeRequest' => function ($event) {
$theme = Yii::$app->settings->get('theme', 'general');
Yii::setAlias('#theme', realpath(dirname(__FILE__)."/../../themes/$theme"));
},
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.
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