在我的 Controller 中有很多代码,大约 1000 行 建议您如何变得更方便,例如在特征中制作一段代码
components/ProductTrait.php
trait ProductTrait{
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;
}
}
Controller
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);
}
}
请您参考如下方法:
您可以使用 Trait,但也可以使用行为。
首先声明你的行为
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;
}
}
然后在 Controller 中使用它(不要忘记附加它,我已经在 init
方法中完成了)
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);
}
}
行为的要点是它可以在 php 5.3 中工作,而特征则不能。
下面是特质
和行为
之间的一些区别:
- 与行为的第一个区别是特征不能参数化。
在你的 Controller 中,你可以这样声明行为:
public function behaviors(){
return array(
'ProductBehavior ' => array(
'class' => 'components.behaviors.ProductBehavior',
'firstAttribute' => 'value',
'secondAttribute' => 'value',
)
);
}
您的 ProductBehavior
类将有 2 个公共(public)属性:firstAttribute
和 secondAttribute
。
与行为相比,特征缺乏的一件事是运行时附加。如果您想使用一些特殊功能扩展给定的(比方说 3rdParty)类,行为可以让您有机会将它们附加到该类(或更具体地说,附加到该类的实例)。使用特征,您必须修改类的源代码。
- The Yii Guide
- The CBehavior doc