CakePHP: calling other Model functions - cakephp

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

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.

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

User App::import()
App::import('Model','OtherModel');
$attr = new OtherModel();
$attr->Othermodelfunction();

if there's a (direct or indirect) relationship between the model, you can call the function: $this->Model1->Model2->...->Modeln->function();
use bindModel

no, you should use ClassRegistry like so:
//MessagesController - in my send() method...
$this->set('content', ClassRegistry::init('Content')->find('first', array(
'conditions' => array('Content.id' => 3)
)));
NOTE:this is from my controller but I am pretty sure it works in model too.

In 2.x versions the $this->Model1->Model2 syntax answered above will not work. Calling functions from another models in many cases is the job of a controller, not the model. Consider that, the model methods should be limited to querying and updating data whilst maintaining database integrity.
1st method: using the controller
I'll illustrate this with an example of Firm and User models, while Firm hasMany users. This method is recommended, if you plan to add extra controller functionality inbetween, such as setting flash messages or cookies.
User model:
public function saveRegisteredUsers($user_data,$firm_id){ ... }
--
FirmsController:
public function add(){
if($this->Firm->save($this->request->data)){
// set $this->Firm->id here
$this->loadModel('User');
$this->User->saveRegisteredUsers($this->request->data['User'],
$this->Firm->id);
// ...
}
}
2nd method: using the model
For this you will need to have correct model associations. The table names have to be users and firms conventionally. Following the terminology of the example above your relation should be defined as this in the Firm model:
public $hasMany = array( 'User' => array(
'className' => 'User',
));
In the User model, you have to set up the belongsTo association properly:
public $belongsTo = array(
'Firm' => array(
'className' => 'Firm',
'foreignKey' => 'firm_id',
'dependent' => false
)
);
After this, you can call $this->User->saveRegisteredUsers() directly from any of the Firm model methods.

If you have a model function that you want to call from many models, the best approach is to abstract any references to the model name ($this->alias) and place the function in AppModel. Then it is accessible in any of your models.
class AppModel extends Model{
public function myFunction($options = array(){
do some stuff with $this->alias;
}
}

Related

How to find a model in cakePHP (I can't find)?

I have taken over a project for cakePHP, I am new and I find it not easy, Magento should be difficult but I find cakePHP more difficult, but maybe I have not reach the moment I know it ...
I have the next model (for table postcodes):
public $belongsTo = array(
'Postcode' => array(
'className' => 'Postcode',
'foreignKey' => 'postcode_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
Everything works, but with the tool AgentRansack I can't find the model Postcode. And besides the name of the table is postcodes, I can't even find a relation for Postcode and postcodes.
How can such a model setup in a different way than with a class Postcode.php ?
When requesting models for which no concrete model class exists (or cannot be found for whatever reason), dynamic model objects will be generated from the AppModel class.
From the CakePHP Cookbook:
CakePHP will dynamically create a model object for you if it cannot find a corresponding file in /app/Model. This also means that if your model file isn’t named correctly (for instance, if it is named ingredient.php or Ingredients.php rather than Ingredient.php), CakePHP will use an instance of AppModel rather than your model file (which CakePHP assumes is missing). If you’re trying to use a method you’ve defined in your model, or a behavior attached to your model, and you’re getting SQL errors that are the name of the method you’re calling, it’s a sure sign that CakePHP can’t find your model and you need to check the file names, your application cache, or both.
http://book.cakephp.org/2.0/en/models.html#understanding-models
By the sounds of it you need to create a class for your 'postcodes',
Read the following: http://book.cakephp.org/2.0/en/models.html
But it should look something like this:
// app/Model/Postcode.php
App::uses('AppModel', 'Model');
class PostCode extends AppModel {
public $validate = array(
// Validation
);
// Replace 'ModelName' with the name of the class where the code sites you mentioned above
public $hasMany = array(
'ModelName' => array(
'className' => 'ModelName',
'foreignKey' => 'postcode_id'
)
);
}

use unassociate model in another model with condition in cakephp [duplicate]

Can I use another Model inside one model?
Eg.
<?php
class Form extends AppModel
{
var $name='Form';
var $helpers=array('Html','Ajax','Javascript','Form');
var $components = array( 'RequestHandler','Email');
function saveFormName($data)
{
$this->data['Form']['formname']=$data['Form']['formname'];
$this->saveField('name',$this->data['Form']['formname']);
}
function saveFieldname($data)
{
$this->data['Attribute']['fieldname']=$data['Attribute']['fieldname'];
}
}
?>
Old thread but I'm going to chime in because I believe the answers to be incomplete and lacking in "why". CakePHP has three ways to load models. Though only two methods work outside of a Controller, I'll mention all three. I'm not sure about version availability but this is core stuff so I believe they'll work.
App::import() only finds and require()s the file and you'll need to instantiate the class to use it. You can tell import() the type of class, the name and file path details.
ClassRegistry::init() loads the file, adds the instance to the object map and returns the instance. This is the better way to load something because it sets up "Cake" things as would happen if you loaded the class through normal means. You can also set an alias for the class name which I've found useful.
Controller::loadModel() uses ClassRegistry::init() as well as adds the Model as a property of the controller. It also allows $persistModel for model caching on future requests. This only works in a Controller and, if that's your situation, I'd use this method before the others.
You can create instances of other models from within any model/controller using one of these two methods.
If you're using Cake 1.2:
App::import('model','Attribute');
$attr = new Attribute();
$attr->save($dataYouWantToSavetoAttribute);
If you're using Cake 1.1:
loadModel('Attribute');
$attr = new Attribute();
$attr->save($dataYouWantToSavetoAttribute);
An obvious solution everyone missed is to create an association between two models, if appropriate. You can use it to be able to reference one model from inside another.
class Creation extends AppModel {
public $belongsTo = array(
'Inventor' => array(
'className' => 'Inventor',
'foreignKey' => 'inventor_id',
)
);
public function whoIsMyMaker() {
$this->Inventor->id = $this->field('inventor_id');
return $this->Inventor->field('name');
}
}
In CakePHP 1.2, it's better to use:
ClassRegistry::init('Attribute')->save($data);
This will do simply
<?php
class Form extends AppModel
{
//...
$another_model = ClassRegistry::init('AnotherModel');
//...
}
?>
In CakePHP 3 we may use TableRegistry::get(modelName)
use Cake\ORM\TableRegistry;
$itemsOb = TableRegistry::get('Items');
$items = $itemsOb->find("all");
debug($items);
If you want to use Model_B inside Model_A, add this line at the beginning of Model_A file:
App::uses('Model_B_ClassName', 'Model');
and then you will be able to use it inside Model_A. For example:
$Model_B = new Model_B_ClassName();
$result = $Model_B->findById($some_id);
var $uses = array('ModeloneName','ModeltwoName');
By using $uses property, you can use multiple models in controller instead of using loadModel('Model Name').
App::import('model','Attribute');
is way to use one model into other model. Best way will be to used association.

CakePHP: Limit associations in the controller

As an example lets imagine we have a simple tv show database. Show and Episode as Model.
An Episode belongsTo one Show and one Show hasMany Episodes.
In the episodes/index view we are just echoing all episodes, the same goes for the shows/index view. But I also want to echo lets say the first 5 episodes of each show (just the title). I could simply limit the episodes by setting the limit attribute for the hasMany association.
In shows/episode/x(id) view I want to echo all episodes. And therefore I can't simply use the limit attribute for the hasMany association since it is view dependent.
What solution should I choose to implement that? I could only archive that by using some "dirty workarounds/hacks" but I feel like this is an usual problem and there might be some actual solution.
I believe what you are looking for is the containable behaviour.
Read the doc:
http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html
Then remove any limit to your associations. Below there is a way of how you can use containable behavior in your example.
class Shows extends AppModel {
public $actsAs = array('Containable');
}
class ShowsController extends AppController {
//Bring all the shows and 5 episodes
public function index(){
$this->Show->find('all', array('contain' => array(
'Episode' => array('limit' => 5)
)));
}
public function view($id){
//Bring the show
$this->Show->findById($id);
//Then bring the episodes of the show
$this->Show->Episode->findByShowId($id);
//Or you can use
$this->Show->find('all', array(
'contain' => array('Episode')),
'conditions' => array('id' => $id)
);
}
}

Table not found, same using useTable

I have a model, called "Cliente" and this model have a association with another table called ClienteRelFot. I declared that ClienteRelFot has a useTable = 'rel_fot_ec', but the cake are looking for "rel_fots".
The rel_fot_ec table exists on my database because I use to find another data.
Someone have a idea to solve this problem?
I tried clear cache and delete all files from tmp folders.
Below, we have the error:
Error: Table rel_fots for model RelFot was not found in datasource default.
Your associations are trying to pull data from the model 'RelFot' (per the error), not 'ClientRelFot', so declaring that 'ClienteRelFot' uses the table 'rel_fot_ec' will have no effect.
Try adding:
public $useTable = 'rel_fots';
in your 'RelFot' model.
I had this problem too, even though using public $useTable = ...
My data model: Event hasMany > Submissions hasMany > Authors
Cake was telling me [MissingTableException] Table authors for model Author ..., the problem was not in the Author model, but in the Submission model:
class Submissions extends AppModel {
public $hasMany = array(
'Author' => array(
'className' => 'authors', // author should be singular
'foreignKey' => 'submission_id'
)
);

Can I use one model inside of a different model in CakePHP?

Can I use another Model inside one model?
Eg.
<?php
class Form extends AppModel
{
var $name='Form';
var $helpers=array('Html','Ajax','Javascript','Form');
var $components = array( 'RequestHandler','Email');
function saveFormName($data)
{
$this->data['Form']['formname']=$data['Form']['formname'];
$this->saveField('name',$this->data['Form']['formname']);
}
function saveFieldname($data)
{
$this->data['Attribute']['fieldname']=$data['Attribute']['fieldname'];
}
}
?>
Old thread but I'm going to chime in because I believe the answers to be incomplete and lacking in "why". CakePHP has three ways to load models. Though only two methods work outside of a Controller, I'll mention all three. I'm not sure about version availability but this is core stuff so I believe they'll work.
App::import() only finds and require()s the file and you'll need to instantiate the class to use it. You can tell import() the type of class, the name and file path details.
ClassRegistry::init() loads the file, adds the instance to the object map and returns the instance. This is the better way to load something because it sets up "Cake" things as would happen if you loaded the class through normal means. You can also set an alias for the class name which I've found useful.
Controller::loadModel() uses ClassRegistry::init() as well as adds the Model as a property of the controller. It also allows $persistModel for model caching on future requests. This only works in a Controller and, if that's your situation, I'd use this method before the others.
You can create instances of other models from within any model/controller using one of these two methods.
If you're using Cake 1.2:
App::import('model','Attribute');
$attr = new Attribute();
$attr->save($dataYouWantToSavetoAttribute);
If you're using Cake 1.1:
loadModel('Attribute');
$attr = new Attribute();
$attr->save($dataYouWantToSavetoAttribute);
An obvious solution everyone missed is to create an association between two models, if appropriate. You can use it to be able to reference one model from inside another.
class Creation extends AppModel {
public $belongsTo = array(
'Inventor' => array(
'className' => 'Inventor',
'foreignKey' => 'inventor_id',
)
);
public function whoIsMyMaker() {
$this->Inventor->id = $this->field('inventor_id');
return $this->Inventor->field('name');
}
}
In CakePHP 1.2, it's better to use:
ClassRegistry::init('Attribute')->save($data);
This will do simply
<?php
class Form extends AppModel
{
//...
$another_model = ClassRegistry::init('AnotherModel');
//...
}
?>
In CakePHP 3 we may use TableRegistry::get(modelName)
use Cake\ORM\TableRegistry;
$itemsOb = TableRegistry::get('Items');
$items = $itemsOb->find("all");
debug($items);
If you want to use Model_B inside Model_A, add this line at the beginning of Model_A file:
App::uses('Model_B_ClassName', 'Model');
and then you will be able to use it inside Model_A. For example:
$Model_B = new Model_B_ClassName();
$result = $Model_B->findById($some_id);
var $uses = array('ModeloneName','ModeltwoName');
By using $uses property, you can use multiple models in controller instead of using loadModel('Model Name').
App::import('model','Attribute');
is way to use one model into other model. Best way will be to used association.

Resources