PHP   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了php – 在行为代码在Yii2中运行之前获取控制器操作大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试在Yii2控制器中执行一些代码,因为我需要在行为部分中可以访问模型中的一些代码,因此我可以将模型作为参数传递并避免运行重复查询;但是我还需要能够找出正在调用的动作,但我没有太多运气.

我已经尝试过使用beforeAction但是它似乎在行为代码运行后运行,所以这对我没有帮助.

然后我尝试使用init,但似乎此操作无法通过$this-> action-> id获得.

一些示例代码

@H_801_7@class MyController extends Controller { public $defaultAction = 'view'; public function init() { // $this->action not available in here } public function beforeAction() { // This is of no use as this runs *after* the 'behaviors' method } public function behaviors() { return [ 'access' => [ 'class' => NewAccessControl::className(),'only' => ['view','example1','example2'],'rules' => [ [ 'allow' => false,'authManager' => [ 'model' => $this->model,'other_param' => $foo,'other_param' => $bar,],'actions' => ['view'],// everything else is denied ],]; } public function viewAction() { // This is how it is currently instantiated,but we want to instantiate *before* the behavior code is run so we don't need to instantiate it twice // but to be able to do that we need to k@L_874_6@ the action so we can pass in the correct scenario $model = new exampleModel(['scenario' => 'view']); } }

authManager只是对AccessRule类扩展中的成员变量的引用.

无论如何我能做到吗?

好吧,如果我找对你,你正在寻找这样的东西: @H_801_7@public function behaviors() { $model = Mymodel::find()->someQuery(); $action = Yii::$app->controller->action->id; return [ 'someBehavior' => [ 'class' => 'behavior/namespace/class','callBACk' => function() use ($model,$action) { //some logic here } ] ]; }

因为behavior()只是一个方法,所以你可以声明任何变量并添加你想要的任何逻辑,你必须遵循的唯一约定 – 返回类型必须是数组.

如果使用自定义行为,则可以使用events()方法将行为的方法绑定到某些事件.例如.

@H_801_7@class MyBehavior extends Behavior { public function events() { return [ \yii\web\User::EVENT_AFTER_LOGIN => 'myAfterLoginEvent',]; } public function myAfterLoginEvent($event) { //dealing with event } }

在此示例中,myAfterLoginEvent将在用户成功登录到应用程序后执行. $event变量将由框架传递,根据事件类型,它将包含不同的数据.阅读about event object

更新:

正如我现在所看到的,我的答案对于事件和行为更为通用.现在,当您添加代码时,我建议您使用以下代码覆盖行为的beforeAction($action)方法

@H_801_7@public function beforeAction($action) { $actionID = $action->id; /* @var $rule AccessRule */ foreach ($this->rules as &$rulE) { $model = &$rule->authManager['model']; //@L_874_6@ set model scenario maybe like this $model->scenario = $actionID; } //@L_874_6@ call parent implementation parent::beforeAction($action); }

另请参阅AccessControl implementation of beforeAction方法,它调用每个规则允许方法将当前操作作为参数传递给它.因此,如果您有扩展AccessRule的类,则可以覆盖allow($action,$user,$request)方法或matchCustom($action)方法来设置适当的模型方案.希望这会有所帮助.

还有一个选择:

覆盖控制器的runAction($id,$params = [])方法.这里$id是actionID – 正是你需要的.检查id,设置适当的模型场景并调用parent :: runAction($id,$params);

大佬总结

以上是大佬教程为你收集整理的php – 在行为代码在Yii2中运行之前获取控制器操作全部内容,希望文章能够帮你解决php – 在行为代码在Yii2中运行之前获取控制器操作所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。