specify request verb for action in Yii2 controller through actions() - php

I know there is a way to specify the request verb in Yii2's routes like this (in routes.php):
[
'POST users' => 'user/create',
'GET users' => 'user/index',
]
but is there a way to do that inside of a controller in the actions() method? like:
class ExampleController extends Controller {
public function actions() {
return [
'create' => [
'class' => ActionCreate::class,
'verb' => 'POST'
],
'index' => [
'class' => ActionIndex::class,
'verb' => 'GET'
]
];
}
}
I tried:
'GET create' => ActionCreate::class
which yii interpreted as a valid route and /user/create showed a 404
and
'create' => [
'class' => ActionCreate::class,
'verb' => 'GET'
]
which said that 'verb' is an unknown property of ActionCreate
The reason I'm asking this is because I want to make my app use as little explicit routing as possible
The other solution for this is to use the same action for both GET and POST and do things differently on the request method but I would like to keep things separated

Yes, you can do it and VerbFilter is made for that.
Usually you are attaching this behavior in the controller and you should do it like that since you are responsible for the actions added.
If somehow adding it in the controller is not possible, you can implement beforeRun() in the action class like:
public function beforeRun()
{
$verb = \Yii::$app->getRequest()->getMethod();
$allowed = [/*list of allowed uppercased verbs here*/];
if (!in_array($verb, $allowed)) {
\Yii::$app->getResponse()->getHeaders()->set('Allow', implode(', ', $allowed));
throw new \yii\web\MethodNotAllowedHttpException('Method Not Allowed. This URL can only handle the following request methods: ' . implode(', ', $allowed) . '.');
}
return true;
}
This is taken straight from the VerbFilter by the way.
And since this is will be a part of action you can prepare some property that will take the allowed verbs so you will be able to config it in controller's actions() method. But as I said, simply adding it in the controller is much simpler.

Related

Catch user defined URLs in UrlManager

I have the ability for users to define URLs for some of their items so, for example:
http://x.com/mynewobject
mynewobject would be defined by the user in a form and I need to be able to say in the UrlManager to math that, but also match everything else.
Problem is the default rules in the UrlManager will try and catch the mynewobject controller and throw a 404 when it cannot.
What is the way to make a UrlManager catch user defined URLs?
The best way I have found of doing this, without manually declaring your URLs, is to actually take a closer look at the Yii 2 documentation.
It actually shows a good example here of user generated URLs http://www.yiiframework.com/doc-2.0/guide-runtime-routing.html#creating-rules which I used to complete my task.
The configuration I used was:
'urlManagerFrontend' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
'cache' => null,
'baseUrl' => '/',
'rules' => [
[
'class' => 'common\components\ObjectUrlRule',
'pattern' => '<slug:.*>',
'route' => 'site/index'
],
'<controller:[\w-]+>/<id:\d+>'=>'<controller>/view',
'<controller:[\w-]+>/<action:[\w-]+>/<id:\d+>'=>'<controller>/<action>',
'<controller:[\w-]+>/<action:[\w-]+>'=>'<controller>/<action>',
// your rules go here
]
],
And a rule class of:
<?php
namespace common\components;
use Yii;
use yii\web\UrlRule;
use common\models\ObjectUrl;
class ObjectUrlRule extends UrlRule
{
public function parseRequest($manager, $request)
{
$pathInfo = trim($request->getPathInfo());
if(!$pathInfo){
return false;
}
$controller = Yii::$app->createController($pathInfo);
if($controller){
return false;
}
$objectUrl = ObjectUrl::find()->where(['url' => $pathInfo])->one();
if(!$objectUrl){
return false;
}
return $objectUrl->getUrl($pathInfo);
}
}
Where ObjectUrl is the model (table) which contains the map of user generated URLs.
The good thing about this class, as well, is that it will not run the database call unless the controller does not exist and there is a pathinfo.

Is it posible to create a urlManager Rule which preloads an object based on ID?

Working with Yii 2.0.4, I'm trying to use urlManager Rule to preload an object based on a given ID in the URL.
config/web.php
'components' => [
'urlManager' => [
[
'pattern' => 'view/<id:\d+>',
'route' => 'site/view',
'defaults' => ['client' => Client::findOne($id)],
],
[
'pattern' => 'update/<id:\d+>',
'route' => 'site/update',
'defaults' => ['client' => Client::findOne($id)],
],
]
]
If this works, it will not be necessary to manually find and object each time, for some CRUD actions:
class SiteController extends Controller {
public function actionView() {
// Using the $client from the urlManager Rule
// Instead of using $client = Client::findOne($id);
return $this->render('view', ['client' => $client]);
}
public function actionUpdate() {
// Using $client from urlManager Rule
// Instead of using $client = Client::findOne($id);
if ($client->load(Yii::$app->request->post()) && $client->save()) {
return $this->redirect(['view', 'id' => $client->id]);
} else {
return $this->render('edit', ['client' => $client]);
}
}
}
NOTE: The above snippets are not working. They're the idea of what I want to get
Is it possible? Is there any way to achieve this?
If you look closer: nothing actually changes. You still call Client::findOne($id); but now doing it in an unexpected and inappropriate place, and if you look at the comment about default parameter it says:
array the default GET parameters (name => value) that this rule provides.
When this rule is used to parse the incoming request, the values declared in this property will be injected into $_GET.
default parameter is needed when you want to specify some $_GET parameters for your rule. E.g.
[
'pattern' => '/',
'route' => 'article/view',
'defaults' => ['id' => 1],
]
Here we specify article with id = 1 as default article when you open main page of site e.g. http://example.com/ will be handled as http://example.com/article/view?id=1
I can suggest to you add property clientModel in to your controller and then in beforeAction() method check if its update or view action then set
$this->clientModel = Client::findOne($id);
and in your action:
return $this->render('view', ['client' => $this->clientModel]);

Laravel rename routing resource path names

Can we rename routing resource path names in Laravel like in Ruby on Rails?
Current
/users/create -> UsersController#create
/users/3/edit -> UsersController#edit
..
I want like this;
/users/yeni -> UsersController#create
/users/3/duzenle -> UsersController#edit
I want to do this for localization.
Example from Ruby on Rails;
scope(path_names: { new: "ekle" }) do
resources :users
end
I know this is an old question. I'm just posting this answer for historical purposes:
Laravel now has the possibility to localize the resources. https://laravel.com/docs/5.5/controllers#restful-localizing-resource-uris
Localizing Resource URIs By default, Route::resource will create
resource URIs using English verbs. If you need to localize the create
and edit action verbs, you may use the Route::resourceVerbs method.
This may be done in the boot method of your AppServiceProvider:
use Illuminate\Support\Facades\Route;
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot() {
Route::resourceVerbs([
'create' => 'crear',
'edit' => 'editar',
]); }
Once the verbs have been customized, a resource route registration such as Route::resource('fotos', 'PhotoController') will
produce the following URIs:
/fotos/crear
/fotos/{foto}/editar
It ain't pretty, but you could define multiple routes that use the same controller function. For example:
Route::get("user/create", "UsersController#create");
Route::get("user/yeni", "UsersController#create");
The only (glaringly obvious downside) being that you're routes will get quite cluttered quite quickly. There is a setting in app/config/app.php where you can set/change your locale, and it could be possible to use that in conjunction with a filter to use the routes and then group those routes based on the current local/language, but that would require more research.
As far as I know, there isn't a way to rename resource routes on the fly, but if you get creative you can figure something out. Best of luck!
You can't change the resource url's.
For this you will need to define/create each route according your needs
Route::get("user/yeni", "UsersController#create");
and if you need more than one languages you can use the trans helper function, which is an alias for the Lang::get method
Route::get('user/'.trans('routes.create'), 'UsersController#create');
I just had the same issue. And managed to recreate some sort of custom resource route method. It probably could be a lot better, but for now it works like a charm.
namespace App\Helpers;
use Illuminate\Support\Facades\App;
class RouteHelper
{
public static function NamedResourceRoute($route, $controller, $named, $except = array())
{
$routes = RouteHelper::GetDefaultResourceRoutes($route);
foreach($routes as $method => $options) {
RouteHelper::GetRoute($route, $controller, $method, $options['type'], $options['name'], $named);
}
}
public static function GetRoute($route, $controller, $method, $type, $name, $named) {
App::make('router')->$type($named.'/'.$name, ['as' => $route.'.'.$method, 'uses' => $controller.'#'.$method]);
}
public static function GetDefaultResourceRoutes($route) {
return [
'store' => [
'type' => 'post',
'name' => ''
],
'index' => [
'type' => 'get',
'name' => ''
],
'create' => [
'type' => 'get',
'name' => trans('routes.create')
],
'update' => [
'type' => 'put',
'name' => '{'.$route.'}'
],
'show' => [
'type' => 'get',
'name' => '{'.$route.'}'
],
'destroy' => [
'type' => 'delete',
'name' => '{'.$route.'}'
],
'edit' => [
'type' => 'get',
'name' => '{'.$route.'}/'.trans('routes.edit')
]
];
}
}
Use it like this in the routes.php:
\App\Helpers\RouteHelper::NamedResourceRoute('recipes', 'RecipeController', 'recepten');
Where the first parameter is for the named route, second the controller and third the route itself.
And something like this to the view/lang/{language}/route.php file:
'edit' => 'wijzig',
'create' => 'nieuw'
This results in something like this:
This is not possible in Laravel as they use code by convention over configuration. A resources uses the RESTfull implementation
Therefore you have to stick to the convention of
GET /news/create
POST /news
GET /news/1
GET /news/1/edit
...

Yii CBaseUrlRule - named parameters for controller action

I have a child class that parses urls customly that extends CBaseUrlRule.
The parseUrl() function must return a string that is 'controller/action', yet what I want to do is to be able to pass named parameters to that action. Is this possible?
For example, a url might be:
catalogName/brand/brandName/product/productname/
What I want is to redirect that path to the Catalog's index action, with that action having:
public function actionIndex($catalogName, $brandName, $productName) {
//do smthng
}
I'd make a simple url rule, but then I need the class to process certain information before parsing the url.
You can use Named Parameter by defing rules in main.php, like :
array(
'components' => array(
......
'urlManager' => array(
'urlFormat' => 'path',
'rules' => array(
'<catalogName>/brand/<brandName>/product/<productname>/' => 'catalog/index',
),
),
),
);

Configure ZF2 route to allow only post requests

How can I configure Zend Framework 2 route to only to allow POST request type?
I've gone through the documentation but no avail.
EDIT
Here is the portion of my DI code
'cv-create' => array(
'type' => 'Zend\Mvc\Router\Http\Segment',
'options' => array(
'route' => '/profile/cv/:type/create',
'defaults' => array(
'controller' => 'Application\Controller\ProfileController',
'action' => 'cv_create',
),
),
),
My actual question is, is there any way to inject the request control as a constraint to this route?
You could extend the Zend\Mvc\Router\Http\Segment class and create a slightly modified version of match(). Since match() has the $request parameter it should be as simple as follows:
public function match(Request $request, $pathOffset = null)
{
if (!$request->isPost())
{
return null;
}
return parent::match($request, $pathOffset);
}
Then use this modified class instead of the standard Segment in the routing configuration.
An alternative approach could be to use the AbstractRestfulController in this case.
http://framework.zend.com/apidoc/2.1/classes/Zend.Mvc.Controller.AbstractRestfulController.html
Only implement the create() method.
in class Zend_Controller_Request_Http
You can disable the other request type .

Categories