CakePHP Controller interaction question
I have two separate controller, view, database combos: Users and Jobs. Users contains: id, name, jobid. Jobs contains: id, name, wage.
In my user container, I want to retrieve my job name and wage to send to the user view. I wanted to know what is the best practices here. I have tried two methods:
1.) $this->requestAction('/Jobs/getArray', array('pass' => user['jobid'])); I heard this is not the best practice, especially if you have a lot of interaction between controllers, which I probably will. It is also a pain to try and do all of the sending and receiving this way.
2.开发者_如何学运维) App::import the jobs Connector. $Jobs = new JobsConnector. $Jobs->getArray($user['jobid']); Any time I try to do this, I get undefined errors. JobConnector::Job does not exist. I then get an error on the find() method, which otherwise is working.
I have spent hours trying to work out both methods and have been pulling my hair out. I am on the verge of going back to my own personal class interaction because of how much of a PitA these class interactions are.
Someone, please help!
Have you tried doing this with table relations instead of request actions? That way you get the related data from one model in the referencing model throughout your app.
I will answer assuming you have a good reason to NOT HAVE ASSOCIATIONS between your two models. If there is a reason to associate them then some of the previous answers are indeed correct.
If you don't have a valid relationship and don't want to join your models in any way then fetching via requestAction is an absolutely correct solution.
Google for "Resuable elements with requestAction" and you will get a bakery article on how to have your elements fetch their own data and cache their own data accordingly.
Mark Story did a post on the performance issues and as long as you don't abuse it, and you cache logically the performance hit is negligible.
3 - loadModel
If the model isn't already in use in the controller - loadModel can be used to make it available:
class FoosController extends AppController {
function foo() {
...
if (!isset($this->Job)) {
$this->loadModel('Job');
}
$array = $this->Job->getArray();
...
}
To expand on what Selino is saying, do you have associations configured? Perhaps a User
would $hasOne = array( 'Job' )
? If so, then in your UsersController
you can access the Job
model as $this->User->Job->find( ... )
.
Check out the associations documentation. There are some good examples in there.
精彩评论