Working with CakePHP 3.0 Entity objects vs CakePHP 2.0 arrays

CakePHP3 finds will now return a ResultSet object that contains entity objects, one per records. You’ll have to work with these objects now instead of arrays. This is the official description of them:

  • Cake\ORM\ResultSet – A collection of results that gives powerful tools for manipulating data in aggregate.
  • Cake\ORM\Entity – Represents a single row result. Makes accessing data and serializing to various formats a snap.

Further down on that page there is even more info about that. Take a look at the ResultSet API. You’ll see that it implements Iterator, you can use it like an array because of that but it’s an object.

Let’s start with the example UsersController.

The UsersTable, formerly known as a Model.

In your App/View/Products/index.ctp put this:

If you add a

in the loop it will show you the Entity object. I’m not pasting the whole long debug output here, skipping a few fields.

As you can see you’re getting an object back not an array any longer. To access the values or “fields” of your entity object just access it as a property of the object, the magic getter will get you the value of it from the protected _properties property of the Entity object.

Now try adding this into the foreach loop.

Output:

Not all fields were converted, fields that contain an object stay an object. Calling toArray() here will convert the object into an array in the case you really want to continue using arrays instead of object. I would not recommend to do so because your’re simply throwing the new features and possibilities objects make possible away!