是否可以创建一个基于ID预加载对象的urlManager规则?

时间:2015-07-23 21:33:43

标签: php yii2

使用Yii 2.0.4,我尝试使用urlManager规则根据URL中的给定ID预加载对象。

  

配置/ 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)],
        ],

    ]
]

如果这样做,对于某些CRUD操作,没有必要每次都手动查找和对象:

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]);
            }
    }

}

注意:上述代码段不起作用。他们了解我想要的东西

有可能吗?有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:0)

如果你仔细观察:没有任何改变。您仍然可以致电Client::findOne($id);,但现在在意外和不适当的地方进行此操作,如果您查看comment about default parameter,则说:

  

对此规则提供的默认GET参数(name =&gt; value)进行排列。   当此规则用于解析传入请求时,此属性中声明的值将注入$ _GET。

如果要为规则指定一些$_GET参数,则需要

默认参数。例如。

[
    'pattern' => '/',
    'route' => 'article/view',
    'defaults' => ['id' => 1],
]

在此处,当您打开网站的主页时,我们将 id = 1的文章指定为默认文章,例如http://example.com/将作为http://example.com/article/view?id=1

处理

我建议您将属性clientModel添加到控制器中,然后在beforeAction()方法中检查其更新视图操作设置

$this->clientModel = Client::findOne($id);

并在你的行动中:

return $this->render('view', ['client' => $this->clientModel]);