Hi, I have a ControllerA (or better it’s a component, but the sense of my question doesn’t change I think) that has a method like this:
public function actionFoo(){
$model = new Model;
/* do something with $model */
}
Now, ControllerB extends ControllerA, so it has already actionFoo(), right? Now, I would like to use same function (so I don’t need to rewrite it) but with ANOTHER model, example: $model = new ModelB;
How to do that? Is it possible or I have to rewrite actionFoo() function for Controller B to use ModelB?
Is the method an actual controller action that can be accessed from outside? If that’s the case I suggest to create a special method that can be accessed by the actual actions:
public function something($model = 'ModelA')
{
$model = new $model;
// ...
}
If another methods of ControllerB should use ModelB too, then it’ll be better to add class property $modelClass = ‘ModelA’ and set it to ‘ModelB’ in ControllerB. Then, in ControllerA methods instantiate models as Y!! suggested:
yes, you’ll have to overload (rewrite) your actionFoo method in ControllerB. Another solution is to paramtrized the model name to use in ControllerB->actionFoo() …assuming they both implement the same interface (which is the case if you use CActiveRecord methods.
class A {
public $modelName = 'modelA';
public function actionFoo()
{
$c = new $this->modelName;
}
}
class B extends A {
public $modelName = 'modelB';
}
or
class A {
public function actionFoo($modelName='modelA')
{
$c = new $modelName;
}
}
class B extends A {
public function actionFoo($modelName='modelB')
{
parent::actionFoo($modelName);
}
}
… but in all cases, you’ll have to overload something : member or method.
I’m having problems… In controllerA I’m using actions to divide my script in several files. So I have:
class ControllerA
{
public function actions()
{
return array(
'foo'=>'application.controllers.foo.FooAction',
);
}
}
Now if I in FooAction file I write:
<?php
class FooAction extends CAction
{
public function run()
{
$model=new model;
}
}
It works as expected. If I do:
<?php
class FooAction extends CAction
{
public function run()
{
$model=new $this->model;
}
}
Yii returns: "Property "FooAction.Model" is not defined. OK, I understand this message so I try to change code in:
<?php
class FooAction extends CAction
{
public function run()
{
$model=new $this->getController()->model;
}
}
But Yii returns: “Parse error: syntax error, unexpected T_OBJECT_OPERATOR in FooAction” line <N>. And I don’t understand this… how to solve it? I would like to use actions in external file because think it’s a good way to keep a clean code.