Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP: calling other Model functions

Tags:

cakephp

How can i call, from a Model, a function present in another model? I would like not to repeat code.

like image 349
Mike Avatar asked Aug 26 '11 12:08

Mike


3 Answers

You should try to have relationships between your models. There are many types of relationships which you can read here...

If you have above said associations, you can access your associated models using:

$this->Model->OtherModel->function();

If your models are not related in any way, you should use:

ClassRegistry::init('OtherModel')->function();

You can check out my question on this where I obtained great answers

like image 169
AlexBrand Avatar answered Oct 22 '22 23:10

AlexBrand


We can use Model relation to call the function in another model. Eg.

$this->Model->ModelOne->find();
$this->Model->ModelOne->customFunc();

If there is no relation in the models, The we can use

$this->loadModel('ModelName');

To use in the model. In this case you can use

$this->ModelName->function();

directly as you've loaded that model.

like image 27
Vins Avatar answered Oct 23 '22 01:10

Vins


User App::import()

App::import('Model','OtherModel');
$attr = new OtherModel();
$attr->Othermodelfunction();
like image 2
Hardik Sondagar Avatar answered Oct 22 '22 23:10

Hardik Sondagar