Php – Arrays vs Objects in view template

arrayobjectPHPtemplatesview

I am wondering, in view templates, what would contribute to me choosing between using arrays or objects for getting things printed out in arrays

{{$user->zip_code}} vs {{$user['zip_code']}}

I'm working in blade templates in Laravel/PHP fwiw.

My feeling is that it makes sense to use objects: we can use methods if we need to to display/format data, it looks a lot cleaner in the views, and bc of how PHP works fails gracefully if the item isn't set (an unset array value will puke, so you either need to make sure all possible properties are present but false, or do a {{(isset($user['zip_code'])) ? $user['zip_code'] : ''}} for everything you use in a view.

However, I have encountered some contrasting opinions like:
the less the view knows about the layers below it, the better. As such, "flat" values (arrays) are better to use in the view.
We should not trust the view not to explode if a value is not set, that should be handled in the controller.

Because our object properties are not encoded in the models in this system, we can't rely on each object always having the same info in a model level.

Wondering if there are other factors at play here. Orr.. Does it not matter

Best Answer

It's a developer perception. The OOP design concept was introduced in PHP with introduction to version 5 and has been a successful one. At the initial level the use of array seems to be much easier than the use of Objects due to the use of pointer notation instead of dot notation as in other OOP based languages. But as you move ahead on the platform OBJECTS will be more preferred way of handling data. It makes the code much better to be maintained in the larger complex system and easier for the other developers from PHP background to understand.

Related Topic