如何在 RESTful Yii2 中将属性设置为不安全?

编程入门 行业动态 更新时间:2024-10-26 10:28:00
本文介绍了如何在 RESTful Yii2 中将属性设置为不安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在 Yii2 中有一个控制器,它将 ActiveController 扩展为 RESTful,我可以使用 PUT 方法更新它.但是,我想将某些属性设置为不安全,因为我不希望它们可更新.

I have a controller in Yii2 that extends ActiveController to be RESTful and I can update it OK using the PUT method. However I would like to set some attributes as unsafe as I don't want them to be updatable.

阅读一些不同的例子,我认为我可以在模型的规则中做这样的事情:

Reading some different examples I thought I would be able to do something like this in the model's rules:

[['first_name','last_name','!password'], 'safe', 'on' => 'update'],

但是这并不能阻止密码被更新.

However this doesn't prevent password being updated.

然后我找到了场景()方法并认为这应该有效:

So then I found the scenarios() method and thought this should work:

public function scenarios() { return [ 'default' => ['*'], // Also tried without this line 'update' => ['first_name','last_name','!password'], ]; }

但这会阻止所有属性更新.

But that prevents all attributes getting updated.

大家还有什么建议吗?

推荐答案

这个规则只是意味着可以大量分配属性(使用 Model::load()),但是,没有任何验证,并且在每种情况下也是如此.

This rule would just mean that the attributes can be massivly assigned (using Model::load()), however, without any validation and also in each scenario.

[['first_name','last_name','password'], 'safe'],

但你也可以在这里使用,例如字符串"而不是安全".然后它也用于每个场景,但现在使用字符串验证.

But you can use here also e.g. 'string' instead of 'safe'. Then it is also used in each scenario but now with string validation.

通过以下内容,您引入了一个更新"场景,并告诉验证引擎 first_name 和 last_name 应该可以大量分配并得到验证,但密码被排除在外.正如您所料.

With the following you introduce an 'update' scenario and you tell the Validation engine that first_name and last_name should be massively assignable and get validated, but password is excluded from that. Like you have expected.

public function scenarios() { return [ 'update' => ['first_name','last_name','!password'], ]; }

还重要的是,在调用 load() 或 save() 之前,在更新或创建时设置场景(在控制器中):

Important is also that you set the scenario on update or creation (in the controller) before you call load() or save():

$model = ... $model->scenario = 'update'; $model->load(...); $model->save();

更多推荐

如何在 RESTful Yii2 中将属性设置为不安全?

本文发布于:2023-11-15 06:30:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1591976.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:设置为   中将   不安全   属性   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!