Why use classes in php?

老子叫甜甜 提交于 2020-07-15 15:11:10

问题


I want to know why we use classes in php. I have seen in all of open source they use classes for executing query. It means they use classes for getting results, insert query etc. I think this is used for consistency and speedup, but as my knowledge if we execute query using mysql_query(), rather than creating an object link $db->query will execute fast as compare to second one because in object it will goto the function and then it execute it there and after that it return the result but in case of mysql_query() it will execute the query on the same place. So I think mysql_query() will execute fast. So why we use classes and object to execute query, what are the benefits of using classes?


回答1:


Encapsulation: A class is a useful packet containing the code and the relevant data together, isolated from everything else. That makes it easier to move it around without searching for exact variables, without collisions with existing code/data.

Of course classes have other uses but in scripting environments like PHP, I think the biggest advantage is that.

EDIT: I was objected with "inheritance is more powerful than encapsulation" argument. I think that does not apply to scripting and web scenarios and I'll try explain why:

First, a web page's lifetime is a request/response pair and ideally less than a second. The state is usually preserved in external entities (session, cookies, db etc). Since the page's lifetime is very short, possible states in a web page code are less than, say, a fat client. It's almost always small bursts of code running and finishing the work continuously. Arguably a web page is comparable to a console application in terms of simplicity and number of design parameters. Although number of input parameters can be gigabytes in a form, the relation between UI elements and input parameters are limited to screen resolution, a user's overall capability to what he/she can fill in at once. Therefore in majority of cases we have small number of input parameters, meaning smaller number of states. Of course in combinatorial and "mutable" world that's not true but in the case of "typical web applications", internal state is also small, hence making my claim plausible.

The input and output in a web application is mostly the same: Input is query parameters or form data and output is an HTML document. Therefore in its short lifetime the input processing and output production code is similarly shaped and designed for a web page. I am aware that I omitted a big chunk of "business logic" in the picture and I'll get to that. However let's make sure that we have no use of nifty features of OOP like "polymorphism" and "inheritance" in these parts of our code. There are very well known, long studied, practical and non-OOP patterns for that. It would be at least dumb to invent new ways of parsing query parameters using "polymorphism", "visitor pattern" etc.

The data access is also performed by existing libraries and luxuries like "inheritance" or "polymorphism" have no use there. You can still use classes but that would simply be encapsulation. You can't inherit/reuse MySQL code for writing T-SQL or PL/SQL code. You need a complete replacement. Oh maybe your SELECT * FROM table could be "inherited", and think of possibilities, wow.

Now what we have left? Yes, the business logic. We already mentioned that business logic is also short bursts of information processing. There is no persistent business state in PHP code itself. We know that almost all business operations must take less than a second due to The Web's requirements. Therefore the states you can go through, again, is much less than a full fledged application. You have atomic, isolated business operations going on for majority of cases in a typical web application.

Now let's go back to design. We know that our page consists of these parts:

  • Input
  • Business logic
    • Data access
  • Output

We already got input, data, output out of the scope of polymorphism and inheritance. Here is our final picture:

  • Input processing
  • Business logic
    • Data access
  • Output production

Although business logic could be the biggest part of our app, it's still got to be in our one second window in a web application therefore has to be small, aka short lived.

Yes a supercomputer can do a lot in a second but we're still talking in terms of majority, common scenarios. What's common? CRUD is common. That's why Ruby on Rails and Active Record pattern is such a success and gained such a popularity because it increased productivity on one thing: CRUD.

The complexity of a design is proportional to the number of data elements and operations involved. And since we assume that majority of operations are CRUD, we have a fixed number of operations and small number of input parameters, we have a small problem space.

There can be exceptions but for most of the cases a design for a small problem space can't be complex and good at the same time. It's very unlikely that you can use inheritance in a web page's design unless there are vast amount of data points and too much redundance going on behind. I repeat, for most of the cases, it's crude CRUD.

Second, (yes there was a first at the beginning in case you forgot), web app performance is important (if not critical) -remember "one second"- and in a scripting environment it's twice as important.

Object-oriented paradigm relies on a very important low-level mechanism for being useful and performant at the same time: pointer indirection. The ability of a CPU reading pointers and jumping to the address pointed by it with almost no difference than jumping to the address directly. That way we can have a virtual method table used for lookups for correct function call and that way compiler can call object's "some()" method without knowing it's exact type because it's just whatever is in the pointer there, yet it still performs like a crazy horse.

That dream ends in the scripting world. You don't have a CPU natively executing instructions. You have bytecodes produced by PHP compiler and that is interpreted by PHP interpreter. Unlike a CPU, PHP interpreter has to deal with higher level concepts like abstractions, classes, types regardless it's a bytecode. The simple pointer indirection for a CPU is a complex set of operations for PHP. Parsing the operation, understanding the operation, making some sanity checks maybe, and finally performing it with another set of bytecodes.

Therefore the overhead of inheritance in a scripting world is orders of magnitudes slower than in a native environment.

That is acceptable of course, as long as gains are more than losses. And thinking of that the performance loss can be recovered in other ways like upgrading, clustering, it doesn't seem like a problem. That's certainly true and here is my final statement:

For most of the scenarios in web application development, an equally maintainable, equally reusable and possibly more performant design could be achieved without calling upon inheritance/polymorphism, therefore encapsulation is the most common and the greatest benefit in PHP, not inheritance.




回答2:


There are many reasons for using classes, or OOP (Object Orientated Programming).

  1. Code reuse
  2. Inheritance
  3. Easier maintainability
  4. Encapsulation

There are many more reasons, you should just look up the advantages/disadvantages of using OOP.




回答3:


Time taken my

$db->query()
mysql_query() 

is almost the same.

We do not use classes to get execute the code faster but to organise them.

As your project gets bigger and bigger, you will have difficulty in managing your code.

If you objects then you can instantiate that object and use them again again, and besides your code has less chances to get messed up with others.

Object Oriented Way of coding is the easiest and best practice for managing your code elegantly and hence produce better results.




回答4:


When we use mysql_query() you have to connect before to the DB with mysql_connect() and mysql_select_db().

Everytimes you make a mysql_connect() it cost.
So you will make one time mysql_connect() and save the $link. And use this link for every mysql_query("...", $link)

In object it's the same but it's more elegant you juste create an instance of the class (so it create a connection to the DB) and use the object has a link.

If you change the DB password, you will change it one time, just in the class.
If you change MySQL for PostgreSQL, you will rewrite your code one time, just in the class. It will not affect the rest of your app.




回答5:


As @frbry said, we use classes for abstraction. Abstraction is needed to manage and reduce complexity. When you are able to "abstract" operations and data, you are able to focus on other things and not think about the implementation of the "isolated and abstracted" things, when doing other things.

It also helps to change the system in the future with smaller impacts on other parts of the code, and again reduce the complexity of a system.

There is a very good MIT lecture from 1986 that is generally about LISP programming, however it also very well describes, why you need to abstract things in procedures (or black boxes they call them) - the point they make is that software development is all about reducing complexity.

Here is the link: http://www.youtube.com/watch?v=2Op3QLzMgSY



来源:https://stackoverflow.com/questions/4872573/why-use-classes-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!