Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

Understanding CakePHP model data

Saturday, December 29th, 2012 by Servage

When working with PHP frameworks, one of the initial obstacles is learning how the frameowkr handles models and model data. Hence how to access database objects, how to manipulate them and how to expect results from finder methods to be formatted. Most frameworks use objects and arrays for this, but they all have their small pitfalls.

In CakePHP the models handle data rather straightforward. First, let’s look at how a basic model is defined in CakePHP:

class Post extends AppModel {
}

Now, inside a controller we could run one of the magic finder methods, which we get for free from the framework, since the model extends AppModel:

class PostsController extends AppController {
    public $helpers = array('Html', 'Form');

    public function index() {
        $this->set('posts', $this->Post->find('all'));
    }
}

The resulting data is a nested array with the following format:

Array
(
    [0] => Array
        (
            [Post] => Array
                (
                    [id] => 1
                    [title] => The title
                    [body] => This is the post body.
                    [created] => 2008-02-13 18:34:55
                    [modified] =>
                )
        )
    [1] => Array
        (
            [Post] => Array
                (
                    [id] => 2
                    [title] => A title once again
                    [body] => And the post body follows.
                    [created] => 2008-02-13 18:34:56
                    [modified] =>
                )
        )
    [2] => Array
        (
            [Post] => Array
                (
                    [id] => 3
                    [title] => Title strikes back
                    [body] => This is really exciting! Not.
                    [created] => 2008-02-13 18:34:57
                    [modified] =>
                )
        )
)

So, all in all the data is returned as arrays in an expected way. It is not returned as objects, which may annoy some.

Understanding CakePHP model data, 4.7 out of 5 based on 3 ratings
Categories: Tips & Tricks

Keywords: ,

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.