Reputation: 680
I am using cakePHP to develop small webpage and trying to graps MVC concept.
I have controller, in which action I am retrieving post with specified ID.
$post = $this->Post->findById($id);
I need to retrieve post title, concatenated with it's id - but I don't wanna do it in controller directly. Of course I could write underneath $post['id'].','.$post['title'], because $post is an array. But this will be needed in many places. Can I extend model somehow to achieve method to do it?
My approach was:
class Post extends AppModel {
public function getTitleWithId() {
return $this->id.','.$this->title;
}
}
But as I saw model object is not exactly last fetched object.
Maybe I just need to create PostEntity object that accepts in constructor an array returned by findById? But maybe there is better solution.
Upvotes: 0
Views: 984
Reputation: 1595
Your approach is right: let all the data managing be in the model.
Although, take a look to Virtual Fields. It will do your concatenating easier:
http://book.cakephp.org/2.0/en/models/virtual-fields.html
Then you can do a find to your virtual field:
$this->Post->find('first', array(
'conditions' => array(
'id' => $id
),
'fields' => array('yourVirtualField')
));
EDIT
Now that I've read again your question, probably you would need to do a behavior:
http://book.cakephp.org/2.0/en/models/behaviors.html
Think of that as a way to have multiple inheritance (not the same, but somewhat the idea goes along). You develop your method on it, and attach this behavior to only the models you need with:
public $actsAs = array('yourBehavior');
Upvotes: 2
Reputation: 37616
In CakePHP, Model
class are manager, not really instance of a Model
(even if the id
is stored in). You could simply pass the id
to your method and return what you want:
class Post extends AppModel {
public $name = 'Post' ;
public function getTitleWithId($id) {
$post = $this->read(null, $id) ;
return $post[$this->name]['id'].','.$post[$this->name]['title'];
}
}
Upvotes: 1