Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use classes in php?

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?

like image 948
Abhishek Avatar asked Feb 02 '11 09:02

Abhishek


4 Answers

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.

like image 163
Sedat Kapanoglu Avatar answered Oct 16 '22 08:10

Sedat Kapanoglu


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.

like image 30
Prisoner Avatar answered Oct 16 '22 09:10

Prisoner


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.

like image 39
Santosh Linkha Avatar answered Oct 16 '22 09:10

Santosh Linkha


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.

like image 2
Joan Avatar answered Oct 16 '22 08:10

Joan