问题
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