如何在控制器中使用Yii特性
在我的控制器中有很多代码,大约1000行 建议如何更方便,例如在trait中生成一段代码 components/ProductTrait.php 控制器如何在控制器中使用Yii特性,yii,traits,Yii,Traits,在我的控制器中有很多代码,大约1000行 建议如何更方便,例如在trait中生成一段代码 components/ProductTrait.php 控制器 class DealerController extends Controller{ use ProductTrait; public function actionView($id){ $model = $this->loadModel($id); if ($model === null) { throw
class DealerController extends Controller{
use ProductTrait;
public function actionView($id){
$model = $this->loadModel($id);
if ($model === null) {
throw new CHttpException(404, 'The requested page does not exist.');
}
$renderParams['productProvider'] = $this->getProductProvider($model);
}
}
你可以使用特质,但也可以使用行为 首先你声明你的行为
class ProductBehavior extends CBehavior
{
protected function getProductProvider(Product $model){
$dataProductProvider = new CActiveDataProvider('Product', array(
'criteria' => array(
'limit' => $pageLimit,
'condition' => 't.creatorId = :creatorId AND t.categoryId =:categoryId',
'order' => 't.created DESC',
'params' => array(
':creatorId' => $model->creatorId,
':categoryId' => $model->categoryId,
),
),
'pagination' => false,
'sort' => false,
));
return $dataProductProvider;
}
}
然后在控制器中使用它(别忘了附加它,我已经在init
方法中完成了)
行为的要点是它在PHP5.3中工作,而trait则不是
现在这里是特征
和行为
之间的一些区别:
- 行为的第一个区别是,特征不能参数化李>
public function behaviors(){
return array(
'ProductBehavior ' => array(
'class' => 'components.behaviors.ProductBehavior',
'firstAttribute' => 'value',
'secondAttribute' => 'value',
)
);
}
您的ProductBehavior
类将有两个公共属性:firstAttribute
和secondAttribute
- 与行为相比,特征缺少的一点是运行时附加性。如果您想用一些特殊的功能扩展一个给定的(比如说第三方)类,行为让您有机会将它们附加到该类(或者更具体地说,附加到该类的实例)。使用traits,您必须修改类的源代码
class DealerController extends Controller{
public function init() {
//Attach the behavior to the controller
$this->attachBehavior("productprovider",new ProductBehavior);
}
public function actionView($id){
$model = $this->loadModel($id);
if ($model === null) {
throw new CHttpException(404, 'The requested page does not exist.');
}
//We use the behavior methods as if it is one of the controller methods
$renderParams['productProvider'] = $this->getProductProvider($model);
}
}
public function behaviors(){
return array(
'ProductBehavior ' => array(
'class' => 'components.behaviors.ProductBehavior',
'firstAttribute' => 'value',
'secondAttribute' => 'value',
)
);
}