createUrl Yii - should we call it on controller view, or doesn't matter?

陌路散爱 提交于 2020-01-05 09:22:27

问题


Should createUrl be called on controller or in views ? It doesn't matter? Or it does matter ?

Is there a rule we should follow ? Like methods that extend ccontroller should be used on controllers and so on .. ?


回答1:


In View you can use this snippet. You can use this snippet everywhere.

Yii::app()->createUrl();

But for me is better to define a url in controller's action, and use simply $some_url var in the view.

class SomeController extends Controller
{
    public function actionSomeAction()
    {
        $params = array(
            'key1' => 'value1',
            'key2' => 'value2',
        );

        $myUrl = Yii::app()->createUrl('controller/action', $params);

        $this->render('some_action', array(
            'my_url' => $myUrl
        ));
    }
}



回答2:


both are fine, when you're in a view $this refers to the current controller. So you can do $this->createUrl() in either controller or view.




回答3:


You can use creating url in your view, it does not effect performance because it does not use any database query. Create Url : Yii::app()->createUrl(); Create absolute url : Yii::app()->createAbsoluteUrl();

You can use $this to use this functions in your view like $this->createUrl();



来源:https://stackoverflow.com/questions/11058772/createurl-yii-should-we-call-it-on-controller-view-or-doesnt-matter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!