cakephp how to refer to the model with a variable in the controller
I want to refer to $this->Model-> ... in the controller. But I want to make the functions generic, so how can I use do that dynamically? I tried $this->$modelname but of course that didn't work.
The CRUD functions will be generic to all models and thus all controllers, with overriding in a couple of cases.
EXAMPLE: Two controllers, one for each model -- Letter and Email. There is letter controller and email controller. Each has CRUD functions. The views are essentially identical, except the models track different information for each (e.g., Letter with send_method). The only thing that varies between them is the fields. I have automated that part, but the controllers are essentially the开发者_运维问答 same thing as one another except for a few minor variations. I want to have a parent class and have it use the model name of the particular model, so I don't have to keep making changes to every controller every time I make a change. But in some instances I need to refer to $this->Model-> ... and I don't know how to do that.
Commplete rewrite based on clarification of OP
At the top of letters_controller.php add:
$this->defaultModel = 'Letter';
And in emails_controller.php add:
$this->defaultModel = 'Email';
In either controller, to reference the model, call
$this->{$this->defaultModel}->function();
Sounds like you're trying to re-invent the wheel: have you checked out the CakePHP Scaffolding section?
精彩评论