배열 대신 객체를 반환하는 이유는 무엇입니까?
저는 워드 프레스에서 많은 작업을하는데 배열보다 객체를 반환하는 함수가 훨씬 더 많다는 것을 알게되었습니다. 특별히 배열을 요청하지 않는 한 데이터베이스 결과는 객체로 반환됩니다. 오류는 객체로 반환됩니다. WordPress 외부에서 대부분의 API는 배열 대신 객체를 제공합니다.
내 질문은 왜 배열 대신 객체를 사용합니까? 대부분의 경우 그다지 중요하지 않지만 어떤 경우에는 물체를 처리하는 것뿐만 아니라 머리를 감싸는 것이 더 어렵습니다. 객체를 사용하는 성능상의 이유가 있습니까?
저는 독학으로 PHP 프로그래머입니다. 저는 인문학 학위를 받았습니다. 컴퓨터 과학의 근본적인 측면을 놓치고 있다면 용서 해주세요. ;)
내가 일반적으로 객체를 선호하는 이유는 다음과 같습니다.
- 객체는 데이터뿐만 아니라 기능도 포함합니다.
- 객체에는 (대부분의 경우) 미리 정의 된 구조가 있습니다. 이것은 API 설계에 매우 유용합니다. 또한 속성을 공개, 보호 또는 비공개로 설정할 수 있습니다.
- 객체는 객체 지향 개발에 더 적합합니다.
- 대부분의 IDE에서 자동 완성은 개체에 대해서만 작동합니다.
읽어야 할 것이 있습니다.
- 개체 대. PHP의 배열
- PHP stdClass : 배열 대신 객체에 데이터 저장
- 언제 stdClass를 사용해야하고 언제 php5 oo 코드에서 배열을 사용해야합니까?
- PHP 객체와 배열
- MySQL 결과 PHP-배열 또는 객체?
- PHP 객체 대 배열 성능 신화
- PHP의 객체 세트 : 어레이 대 SplObjectStorage
- 더 나은 객체 지향 배열
이것은 아마도 몇 년 동안 대규모 소프트웨어 프로젝트에서 작업하기 전까지는 깊이 이해하지 못할 것입니다. 많은 새로운 컴퓨터 과학 전공자들이 모든 올바른 단어 (캡슐화, 데이터 기능 및 유지 관리 가능성)로 답을 제공하지만 그 모든 것이 왜 좋은지 이해하는 사람은 거의 없습니다.
몇 가지 예를 살펴 보겠습니다.
- 배열이 반환 된 경우 모든 값을 미리 계산하거나 더 복잡한 값을 작성할 수있는 많은 작은 값을 반환해야합니다.
WordPress 게시물 목록을 반환하는 API 메서드를 생각해보십시오. 이 게시물에는 모두 저자가 있고, 저자는 이름, 이메일 주소, 심지어 약력이있는 프로필도 있습니다.
배열의 모든 게시물을 반환하는 경우 게시물 ID 배열을 반환하도록 제한해야합니다.
[233, 41, 204, 111]
또는 다음과 같은 대규모 배열을 반환합니다.
[ title: 'somePost', body: 'blah blah', 'author': ['name': 'billy', 'email': 'bill@bill.com', 'profile': ['interests': ['interest1', 'interest2', ...], 'bio': 'info...']] ]
[id: '2', .....]]
ID 목록을 반환하는 첫 번째 경우는 그다지 도움이되지 않습니다. 그러면 해당 게시물에 대한 정보를 얻기 위해 각 ID에 대해 API 호출을해야하기 때문입니다.
두 번째 경우는 90 %의 시간에 필요한 것보다 더 많은 정보를 가져오고 더 많은 작업을 수행하게됩니다 (특히 이러한 필드 중 하나라도 구축하기가 매우 복잡한 경우).
반면에 객체는 필요한 모든 정보에 대한 액세스를 제공 할 수 있지만 실제로 해당 정보를 아직 가져 오지 않았습니다. 객체를 사용할 때 필드의 값을 결정하는 것은 느리게 (즉, 값이 필요하고 사전에 필요하지 않은 경우) 수행 될 수 있습니다.
- 어레이는 의도 한 것보다 더 많은 데이터와 기능을 노출합니다.
반환되는 대규모 배열의 예로 돌아갑니다. 이제 누군가는 포스트 배열 내의 각 값을 반복하고 인쇄하는 애플리케이션을 빌드 할 수 있습니다. 해당 포스트 배열에 하나의 추가 요소 만 추가하도록 API가 업데이트되면 애플리케이션 코드가 중단 될 것입니다. 왜냐하면 아마 안될 새 필드를 인쇄하기 때문입니다. API가 반환 한 포스트 배열의 항목 순서가 변경되면 애플리케이션 코드도 손상됩니다. 따라서 배열을 반환하면 개체가 만들지 않을 모든 종류의 가능한 종속성이 생성됩니다.
- 기능성
객체는 유용한 기능을 제공 할 수 있도록 내부에 정보를 보유 할 수 있습니다. 예를 들어, post 객체는 이전 또는 다음 게시물을 반환 할만큼 똑똑 할 수 있습니다. 어레이는 당신을 위해 그렇게 할 수 없습니다.
- 적응성
All of the benefits of objects mentioned above help to create a more flexible system.
My question is, why do they use objects instead of arrays?
Probably two reasons:
- WordPress is quite old
- arrays are faster and take less memory in most cases
- easier to serialize
Is there a performance reason for using an object?
No. But a lot of good other reasons, for example:
- you may store logic in the objects (methods, closures, etc.)
- you may force object structure using an interface
- better autocompletion in IDE
- you don't get notices for not undefined array keys
- in the end, you may easily convert any object to array
(For example, in Ruby, everything is an object. PHP was procedural/scripting language previously.)
WordPress (and a fair amount of other PHP applications) use objects rather than arrays, for conceptual, rather than technical reasons.
An object (even if just an instance of stdClass) is a representation of one thing. In WordPress that might be a post, a comment, or a user. An array on the other hand is a collection of things. (For example, a list of posts.)
Historically, PHP hasn't had great object support so arrays became quite powerful early on. (For example, the ability to have arbitrary keys rather than just being zero-indexed.) With the object support available in PHP 5, developers now have a choice between using arrays or objects as key-value stores. Personally, I prefer the WordPress approach as I like the syntactic difference between 'entities' and 'collections' that objects and arrays provide.
My question is, why do they (Wordpress) use objects instead of arrays?
That's really a good question and not easy to answer. I can only assume that it's common in Wordpress to use stdClass
objects because they're using a database class that by default returns records as a stdClass
object. They got used to it (8 years and more) and that's it. I don't think there is much more thought behind the simple fact.
syntactic sugar for associative arrays -- Zeev Suraski about the standard object since PHP 3
stdClass
objects are not really better than arrays. They are pretty much the same. That's for some historical reasons of the language as well asstdClass
objects are really limited and actually are only sort of value objects in a very basic sense.stdClass
objects store values for their members like an array does per entry. And that's it.- Only PHP freaks are able to create
stdClass
objects with private members. There is not much benefit - if any - doing so. stdClass
objects do not have any methods/functions. So no use of that in Wordpress.- Compared with
array
, there are far less helpful functions to deal with a list or semi-structured data.
However, if you're used to arrays, just cast:
$array = (array) $object;
And you can access the data previously being an object, as an array. Or you like it the other way round:
$object = (object) $array;
Which will only drop invalid member names, like numbers. So take a little care. But I think you get the big picture: There is not much difference as long as it is about arrays and objects of stdClass
.
Related:
- The code looks cooler that way
- Objects pass by reference
- Objects are more strong typed then arrays, hence lees pron to errors (or give you a meaningful error message when you try to use un-existing member)
- All the IDEs today have auto-complete, so when working with defined objects, the IDE does a lot for you and speeds up things
- Easilly encapsulate logic and data in the same box, where with arrays, you store the data in the array, and then use a set of different function to process it.
- Inheritance, If you would have a similar array with almost but not similar functionality, you would have to duplicate more code then if you are to do it with objects
Probably some more reason I have thought about
Objects are much more powerful than arrays can be. Each object as an instance of a class can have functions attached. If you have data that need processing then you need a function that does the processing. With an array you would have to call that function on that array and therefore associate the logic yourself to the data. With an object this association is already done and you don't have to care about it any more.
Also you should consider the OO principle of information hiding. Not everything that comes back from or goes to the database should be directly accessible.
There are several reasons to return objects:
Writing
$myObject->property
requires fewer "overhead" characters than$myArray['element']
Object can return data and functionality; arrays can contain only data.
Enable chaining:
$myobject->getData()->parseData()->toXML();
Easier coding: IDE autocompletion can provide method and property hints for object.
In terms of performance, arrays are often faster than objects. In addition to performance, there are several reasons to use arrays:
The the functionality provided by the array_*() family of functions can reduce the amount of coding necessary in some cases.
Operations such as count() and foreach() can be performed on arrays. Objects do not offer this (unless they implement Iterator or Countable).
It's usually not going to be because of performance reasons. Typically, objects cost more than arrays.
For a lot of APIs, it probably has to do with the objects providing other functionality besides being a storage mechanism. Otherwise, it's a matter of preference and there is really no benefit to returning an object vs an array.
An array is just an index of values. Whereas an object contains methods which can generate the result for you. Sure, sometimes you can access an objects values directly, but the "right way to do it" is to access an objects methods (a function operating on the values of that object).
$obj = new MyObject;
$obj->getName(); // this calls a method (function), so it can decide what to return based on conditions or other criteria
$array['name']; // this is just the string "name". there is no logic to it.
Sometimes you are accessing an objects variables directly, this is usually frowned upon, but it happens quite often still.
$obj->name; // accessing the string "name" ... not really different from an array in this case.
However, consider that the MyObject class doesn't have a variable called 'name', but instead has a first_name and last_name variable.
$obj->getName(); // this would return first_name and last_name joined.
$obj->name; // would fail...
$obj->first_name;
$obj->last_name; // would be accessing the variables of that object directly.
This is a very simple example, but you can see where this is going. A class provides a collection of variables and the functions which can operate on those variables all within a self-contained logical entity. An instance of that entity is called an object, and it introduces logic and dynamic results, which an array simply doesn't have.
Most of the time objects are just as fast, if not faster than arrays, in PHP there isn't a noticeable difference. the main reason is that objects are more powerful than arrays. Object orientated programming allows you to create objects and store not only data, but functionality in them, for example in PHP the MySQLi Class allows you to have a database object that you can manipulate using a host of inbuilt functions, rather than the procedural approach.
So the main reason is that OOP is an excellent paradigm. I wrote an article about why using OOP is a good idea, and explaining the concept, you can take a look here: http://tomsbigbox.com/an-introduction-to-oop/
As a minor plus you also type less to get data from an object - $test->data is better than $test['data'].
I'm unfamiliar with word press. A lot of answers here suggest that a strength of objects is there ability to contain functional code. When returning an object from a function/API call it shouldn't contain utility functions. Just properties.
The strength in returning objects is that whatever lies behind the API can change without breaking your code.
Example: You get an array of data with key/value pairs, key representing the DB column. If the DB column gets renamed your code will break.
Im running the next test in php 5.3.10 (windows) :
for ($i = 0; $i < 1000000; $i++) {
$x = array();
$x['a'] = 'a';
$x['b'] = 'b';
}
and
for ($i = 0; $i < 1000000; $i++) {
$x = new stdClass;
$x->a = 'a';
$x->b = 'b';
}
Copied from http://atomized.org/2009/02/really-damn-slow-a-look-at-php-objects/comment-page-1/#comment-186961
Calling the function for 10 concurrent users and 10 times (for to obtain an average) then
- Arrays : 100%
- Object : 214% – 216% (2 times slower).
AKA, Object it is still painful slow. OOP keeps the things tidy however it should be used carefully.
What Wordpress is applying?. Well, both solutions, is using objects, arrays and object & arrays, Class wpdb uses the later (and it is the heart of Wordpress).
It follows the boxing and unboxing principle of OOP. While languages such as Java and C# support this natively, PHP does not. However it can be accomplished, to some degree in PHP, just not eloquently as the language itself does not have constructs to support it. Having box types in PHP could help with chaining, keeping everything object oriented and allows for type hinting in method signatures. The downside is overhead and the fact that you now have extra checking to do using the “instanceof†construct. Having a type system is also a plus when using development tools that have intellisense or code assist like PDT. Rather than having to google/bing/yahoo for the method, it exists on the object, and you can use the tool to provide a drop down.
Although the points made about objects being more than just data are valid since they are usually data and behaviour there is at least one pattern mentioned in Martin Fowler's "Patterns of Enterprise Application Architecture" that applies to this type of cenario in which you're transfering data from one system (the application behind the API) and another (your application).
Its the Data Transfer Object - An object that carries data between processes in order to reduce the number of method calls.
So if the question is whether APIs should return a DTO or an array I would say that if the performance cost is negligible then you should choose the option that is more maintainable which I would argue is the DTO option... but of course you also have to consider the skills and culture of the team that is developing your system and the language or IDE support for each of the options.
참고URL : https://stackoverflow.com/questions/6710967/why-return-object-instead-of-array
'program story' 카테고리의 다른 글
ASP : CheckBox에 대한 OnClick 대 OnClientClick? (0) | 2020.09.22 |
---|---|
가상이 아닌 방법을 재정의 할 수 있습니까? (0) | 2020.09.22 |
Visual Studio : "빌드 실패, 마지막 성공 여부"다시 활성화 (0) | 2020.09.22 |
자바 스크립트 변수 정의 : 쉼표 대 세미콜론 (0) | 2020.09.22 |
std :: system_clock과 std :: steady_clock의 차이점은 무엇입니까? (0) | 2020.09.22 |