开发者

Why is passing data in arrays not discouraged in CodeIgniter?

开发者 https://www.devze.com 2023-02-28 04:54 出处:网络
I come from a Java background and have only recently started learning PHP and CodeIgniter. While I find the framework awesome for its clean design and impressive documentation, I notice that the fram

I come from a Java background and have only recently started learning PHP and CodeIgniter.

While I find the framework awesome for its clean design and impressive documentation, I notice that the framework doesn't necessarily discourage the use of data arrays instead of value objects for passing data around. For ex., the database queries return the result in an array which you can then pass over to the 开发者_开发技巧views for rendering. Similarly, most of the core library methods take associative arrays as inputs.

This, to me, seems like a bad design for an Object Oriented language which should promote and maybe even enforce using value objects for their obvious benefits of encapsulation.

Is this really an example of bad design or simply a matter of style/preference ? Are there any obvious benefits of using arrays for data over a more OO approach ?


Don't be misled by the myth that "everything has to be an object" for your code to be "good Object Oriented design". When you start trying to formulate rationalisations that "I shouldn't be allowed to do this, because it's not good OOP", you're programming backwards.

When you want a list of pieces of data, a data array will suffice. Indeed, it's appropriate.


Why build a complicated object structure when a hash will do? IMHO, many things in the java world are over-engineered. This opinion seems to be shared with many dynamic languages and toolsets, such as Ruby on Rails.


An array is an object and perfectly valid to use for passing data around. No need to define your own class when a built in one will do.


PHP is not an object oriented language. It's an hybrid language.

Arrays are used everywhere because they are significantly more powerful than in other languages (Java in particular). And behind the scenes both arrays and objects use the same dictionary implementation in PHP.

If you want to objectize arrays, then wrap them in:

 $array = new ArrayObject($array, ArrayObject::ARRAY_AS_PROPS);

Or you can just typecast an array 1:1 into an value object:

 $obj = (object) $array;

And back:

 $array = (array) $obj;

They work alike in quite a few contexts anyway (foreaching over them is easy).


Well, an obvious reason to use value objects instead of associative arrays is that if you're passing data in an array all around the place and then you have to change the name of a db table column, you'll have to update the way you access it everywhere in your code, whereas if you have a value object, you need to update only a one line (inside the VO constructor)

0

精彩评论

暂无评论...
验证码 换一张
取 消