Advantages of using Object-Oriented PHP? Where to use?

Asked

Viewed 7,197 times

15

Lately I did a mini social media and practically did not use object orientation, except for one class I did for CRUD with PDO and ready-made Github libraries.

Would this concept be applied more to building libraries and Apis? I saw some design patterns, but I didn’t fit any directly into building a web system.

What is the actual use of OO in PHP? Some example of how to apply OO on a website?

2 answers

17


TL;DR

Object Orientation (OO), regardless of the language and how much it adheres to the theory, can bring the same benefits, the main ones being related to code organization, ease of maintenance and functionality extension capacity.

You’re right to assume that OO is better for libraries and Apis, since code made for third-party use needs to have a well-defined interface, extensibility and encapsulation, while too much flexibility generates headaches to handle code evolution.

However, this paradigm, by itself, does not solve any of the problems and, if misused, can cause as much or more damage than helping.

You don’t need O

That’s what you read. You can do everything you do with objects using only procedural programming.

A good programming language basically needs 3 components:

  • Basic data structures: vectors, maps, classes, simple types, etc.
  • Control structures: if, for, etc..
  • Code organization structures: subroutines, blocks, functions, methods, etc.

Now, think about what classes are, for example. These are a composite of organized code snippets (methods), which contain control logic, and a set of data or attributes (object state) that we call in PHP $this.

Well, you can get the same result using a set of functions and a shared data structure between them. Who knows how to program a little in C, for example, knows very well.

Procedural example:

$this = criar_estrutura();
fazer_algo($this);

Example OO:

$objeto = new Classe();
$objeto->fazer_algo();

The two codes do the same thing, however in the first the state is explicit and needs to be passed on each call to the set of functions that are analogous to the methods of a class.

However, as I intend to show below, OO brings other benefits and it is not by chance or coincidence or a simple fashion that makes it become the most used paradigm in the world.

You can find good materials here in the OS on OO advantages, being an example this question.

What distinguishes Object Orientation

A great differential of OO in relation to other paradigms is that it goes beyond in relation to the abstraction and encapsulation of data.

Of course, nothing’s free. With the benefits come side effects, namely greater ceremony, complexity and constraints, as well as impacts on memory management and performance (not to say that necessarily a system will stay slow or heavy just for using OO).

However, what we see in general is that the gain can be much higher than the price paid by play within the rules of the objects.

When you have private attributes encapsulating the state of an object, it can be "boring" to have to access everything by methods. In theory (but it has to be very theoretical), a good programmer does not need to hide his data structures, only take care not to be tempted to tamper with what should not.

However, if we look at real projects that involve real products, we find that it is an illusion to think that humans will simply follow all the rules and good practices correctly. In a complex project, it can be humanly impossible to be aware of the operation of everything.

Can anyone argue that just study the PHP API to learn how to use the functions, but in real projects you also need to learn the particular system API and other systems with which you do integration, sometimes more complex and disorganized than the language itself (if it is possible :P).

Given this chaotic scenario, the restrictions, standards and rules imposed by OO are very welcome in many cases.

Abstraction and reuse

How do you reuse code without OO? With functions. And how do you add variations? Parameters.

The problem with this is that in the course of time you will need to change the parameters. It is not uncommon for PHP code to find functions with 10 parameters, some optional, others unnecessary. And if you need to remove a parameter, you will have to scan the code looking for the calls.

An alternative to this is to receive vectors, maps or other generic structures as parameters. This may work well to some extent.

When using objects, you can different constructors and have methods to define specific properties that are usually optional.

Let’s now go to a scenario where you have a routine that processes an entity with several attributes, 2 of them being mandatory and the other optional.

An OO implementation could be:

$cliente = new Cliente($cpf, $nome);
$cliente->setEndereco($end);
$email->enviar($cliente);

A simplistic procedural version would be:

enviar_email_cliente($cpf, $nome, null, null, $end); //demais parâmetros omitidos

A more flexible version:

enviar_email_cliente($cpf, $nome, array("endereco" => $end));

Consider also that this system is a great ERP, composed of modules developed by different teams, and there are hundreds of routine calls and in none of them the values are static as in the example.

Now imagine that it was necessary to remove the attribute endereco of the entity Cliente and move to another entity, since now customers can have multiple addresses.

Now goes the question: what happens when you make the change? In which case the IDE or interpreter will warn you that the attribute no longer exists?

This is a trade-off between flexibility and security. A lot of flexibility, as allowed and even encouraged in PHP, is also a frequent cause of hard-to-find errors.

Encapsulation

I can imagine that in your system you have a handful of variables, some global, to exchange information between functions. If not, congratulations, but this is not the rule.

The problem with shared variables is that you risk a chunk of code inadvertently interfering with others.

Let’s take another example. You want to monitor the time of a very time-consuming routine. A naive procedural approach using a global variable would be:

iniciar_timer();
foreach ($planetas as $planeta) {
    popular($planeta);
}
echo "Total: " . finalizar_timer();

Well, obviously this works, but it doesn’t help much. The routine takes a long time and we don’t know which planet we’re having the most difficulties in popular. We want to know the total time as well as the individual time.

We could improve as follows:

$inicio_geral = iniciar_timer();
foreach ($planetas as $planeta) {
    $inicio_parcial = iniciar_timer();
    popular($planeta);
    echo "Planeta $planeta: " . finalizar_timer($inicio_parcial);
    echo "Parcial: " . (time() - $inicio_geral);
}
echo "Total: " . finalizar_timer($inicio_geral);

Okay, now we no longer have the global state and we can reuse the routine.

However, it was found that the process is leaking a lot of memory and wants to investigate when it occurs. For this we need to recover the amount of memory allocated before performing the routine and the amount of memory after it run and add this information to a log file.

How can we change the routines to do that without tampering with the code? Keep in mind that these routines are being used by other people who contribute to the colonization of the galaxy.

If we don’t want global variables, we can change the return of routine inicar_timer to return an array containing both time and memory and thus retrieve both values in finalizar_timer.

However, you are potentially breaking the implementation of several people, since now the echo will not print what you expected. All this because smart programmers, knowing that you returned a timestamp, directly accessed the value.

One can argue that it is possible to fix this simply. For example:

$inicio_geral = iniciar_timer();
foreach ($planetas as $planeta) {
    $inicio_parcial = iniciar_timer();
    popular($planeta);
    imprimir_tempo("Planeta $planeta", $inicio_parcial);
    imprimir_tempo("Parcial, $inicio_geral);
}
imprimir_tempo("Total", $inicio_geral);

Excellent. Now explain to the world why once again incompatible changes were implemented with previous versions and now everyone will have to stay using an old version of your code or stop what they are doing by searching for all the uses of the affected routines, adjusting and testing everything again.

OO does not solve all problems, but in this example (and in several others I see in everyday life) a correct state encapsulation could have solved the whole problem at first. On the other hand, the lack of encapsulation, tends causing this kind of problem.

At this point, OO’s restrictions and bureaucracies would have allowed all changes to be made without interruption and without introducing incompatibilities:

$geral = new Timer();
foreach ($planetas as $planeta) {
    $parcial = iniciar_timer();
    popular($planeta);
    $parcial->logTime("Planeta $planeta");
    $geral->logTime(Parcial);
}
$geral->logTime("Total");

In short: restrictions imposed by OO increase reuse because they limit the way client code can interact with data.

In functional programming, on the other hand, we could still have a method that automatically counts. Example:

monitorar_execucao("Total", function() {
    foreach ($planetas as $planeta) {
        monitorar_execucao("Planeta $planeta", function() { 
            popular($planeta);
        });
    }
});

In the example above, the start and end logs are done automatically and we can add any desired monitoring mechanisms.

And if we want to give a little more flexibility, we can still provide an object as a parameter:

monitorar_execucao("Total", function($timer_global) {
    foreach ($planetas as $planeta) {
        monitorar_execucao("Planeta $planeta", function($timer_parcial) { 
            popular($planeta);
            $timer_global->log("parcial");
        });
    }
});

Note how we use functional programming and OO together to achieve a more flexible, secure and consistent API. We can change the internal implementation without affecting who uses the routine.

Entities

You probably have some entities saved in a database.

Without object orientation, it is not uncommon to use a set of variables or even a map or array to store such data structures.

For example:

$carrinho = ["Pão", "Leite"];

Unless your system is too trivial, you may have encountered some problems while creating routines to retrieve, insert or alter data. Now you forget which attributes a map loads, now you need to pass a lot of values per parameter, etc. Adding fields can turn a nightmare further forward.

Now in quantity:

$carrinho = [
    ["desc" => "Pão", "quantidade" => 2], 
    ["desc" => "Leite", "quantidade" => 1] 
];

Now with unit value

$carrinho = [
    ["desc" => "Pão", "quantidade" => 2, "valor" => .50], 
    ["desc" => "Leite", "quantidade" => 1, "valor" => 2.0] 
];

Excellent, you don’t need anything else to have me shopping cart. We will calculate the total:

$total = 0;
foreach($carrinho as $item) 
    $total += $item['valor'];

If there are multiple locations in your application where you need to browse, add, remove, search elements and so on, you have basically two options. One is to manually access everything as in the example above, and when changes occur (such as new fields), you go around changing everywhere. Another is to create various functions to manipulate the data structure, such as adicionar_item($carrinho, $item) and consultar_item($carrinho, $descricao).

Notice how all this sounds exactly like my first example of OO vs. procedural. We can solve all this without OO, but let’s face it, we are reinventing the wheel and manually doing what we could delegate to the PHP interpreter to do more securely.

Going further, but let’s imagine that you now have carts with many items and often need to go through all the elements to total or query the items. First you think about changing the structure to something like:

$carrinho = [
    "total" => 2,
    "items" => [
        "Pão" => ["quantidade" => 2, "valor" => .50], 
        "Leite" => ["quantidade" => 1, "valor" => 2.0] 
    ]
];

Solves the problem, but will break all the current code once again if you do not all access via own functions.

But of course you don’t need objects. It’s enough that each procedural module has written in the documentation something like "do not access data structures directly!" And from there you can obviously trust that everyone, including you, never will respect this wish and correctly use your API. Good luck! :)

Once again:

  • Lack of encapsulation is a common source of problems.
  • It is complicated to maintain consistency having only a "loose" set of routines.
  • This also makes it difficult for other people to create new routines and create new features on top of their own, as it is unclear how they may or may not use their data structure, while with classes it would be more obvious.

Objects representing complex entities are very safely manipulated by the various system routines with a well-defined interface in a class.

Using the validation example, a well-encapsulated object ensures the internal consistency of the data, which is not so simple with isolated functions. Of course you can create a validation routine and call in each function, but it is not as efficient in many cases preventing having to analyze in each routine the entire received structure to determine whether the state is valid. This leads many libraries not to perform sufficient validation, resulting in difficulties identifying problems when unexpected values appear.

The potential of PHP in different paradigms

You can solve a range of problems using only a specific paradigm, but almost always, for a non-trivial application a single paradigm is not the best or sufficient choice.

When we talk about procedural, functional and object-oriented programming, we should think about how we can use all paradigms in harmony for a better solution.

Object orientation is important and all major languages have some level of support for it or have variations to support the paradigm, such as C++.

Functional programming is another paradigm that all languages seek to harness to some extent. Even languages like Java, traditionally not friendly to this paradigm, embraced it vehemently in its version 8.

Procedural programming is, to a certain extent, inevitable. We are not yet at the stage (and I’m not sure we will) where everything can be solved by functional expressions. Good old control structures such as if and for will still exist within the methods and functions.

The interesting thing about PHP is that it has reasonable support for all these paradigms, although some are better explored than others.

The language is well known for being easy to learn, where someone can have some code running successfully on their first day, if not in the first hour.

Because of this, part of the community encounters difficulties with the use of OO and even functional programming since they are concepts that take longer to digest, in addition to which PHP has a very strong procedural heritage and virtually all modules have a procedural API, sometimes supporting OO at the same time or mixing objects with isolated functions.

I see a movement of the PHP community towards the use of other paradigms, but less for functional programming, which is a shame.

Finally, it would be good to see the three paradigms working together allowing better solutions in all areas.

Examples where Object Orientation is bad

Places where generally OO is not legal or is only used indirectly include:

  • Templates, for example, like Wordpress HTML templates where you mix control logic with HTML code. Even in other languages this is true. Although auxiliary objects (helpers) are used, a text template is intrinsically procedural in its nature.
  • Stateless functions (stateless) neither store nor share variables, nor have prerequisites. For example, even in a purely OO language, a routine to convert an integer into text need not necessarily be in an object. Java, for example, uses static method for these cases.
  • High performance routines work better with simple data structures.

Standards of Projects

Several free code projects die due to lack of maintenance due to poor structuring, because no one can or has the courage to move. Regardless of the paradigm used, it is important to learn best practices.

Design patterns are not unique to the OO Programming paradigm, but are known solutions to specific problems, plus a common language for you not to reinvent the wheel and call "round cube".

Knowing design patterns can teach you how other people have solved certain types of problems and once you learn some you will notice one good thing and another bad thing:

  • The good news is that you will learn other ways to think about the problem you would not have done alone and soon you will be adjusting and composing these different patterns in new ways. So you use the experience of others to grow faster.
  • The bad news is that you start wanting to apply the patterns to everything and end up creating some little monsters until you learn (hopefully) to use these new powers responsibly.

Considerations

Not only in libraries or frameworks, the use of Object Orientation is welcome in any functionality of your program, especially when you aim to reuse and communicate between different parts of the code at the same time you aim for certain encapsulation to avoid problems further ahead.

Use whatever paradigm is best to solve each problem, including all together. But for this you will need to know all, beyond the good and bad practices of each.

  • Thanks for the answer gave to understand a lot on the subject, on the global think I did not use no, in the project itself only used functions and classes in a mini class I created to crud, the variables were distinguished by files.. One question that remained was to do with the question related to this, there says that it is not indicible to mix OO with structured, so I have no idea not to make this mixture because it would be a class for each page?

  • @utluiz I think it was clear, so much so that already received 4 votes and I already received negative. I expected, what I say goes against the tide and then the negative person because of it. Or it is someone who chases me who seizes the chance :). But the first is more likely. Mine is as well founded as yours, IE, none is much, can not substantiate much without writing a thesis. If that were the reason for the negative, then both deserve it. The reason is the disagreement. So that it exists, I do not understand why people have not learned that the vote is not for this. The answer is good.

  • 1

    @Bacco Reformulated question. But the more it grows, the more complicated it becomes. I think I’ve done more justice to the other paradigms now. :)

  • @Edilson You should have kept reading. ;)

  • 4

    @Edilson More patience. First you need to understand that it is somewhat ironic. You can program in binary as well. But not to leave you on hold, forward that my text is a defense of the POO. Basically my argument is that the fact that you don’t need something doesn’t mean it’s not better if you use it. Honestly, I suggest you don’t add criticism like that without reading to the end.

  • 2

    @Edilson has already stopped to consider that maybe the parties you do not agree are correct, and maybe your eyesight is a little "cast"? I am not saying that this is the case, but sometimes it is nice to understand that the authors of both answers did not invent overnight what they are writing, and surely there is a reason for each point they expressed. If any party did not like it I think it’s cool you manifest (I did it before in this same answer, for reasons other than yours), but I think it’s really cool to see and take advantage of everything the answer has to add too.

  • 1

    @Edilson at this point I quite agree with utluiz. And I will say something that I did not have the opportunity to speak in my reply. OOP as implemented so far in PHP is well done. It’s full of holes. And this is just one more reason to avoid its use in this language. I’m not an expert but I study the subject a lot because I like languages and paradigms. I’m not talking about whether I like it or not, whether I think it’s useful or not, I’m talking about being good or not. I think utluiz did the opposite of what you claim. Most people don’t understand OOP, I don’t know if I do. You’ll like mine less

  • @Bacco, bigown, author, I read the whole answer, just not to get with "ideas" like you said yourself, and I didn’t say I don’t agree with anything, except of course that Heading there explicitly saying not to use, perhaps the will of the author was contrary to what actually says the title, as just quoted, but it is a title that partly loses the suggestive content. I did not doubt the only written word in the reply, it was only the title of the point in question, which makes clear the same idea present in other responses related to OOP here in Sopt, of course, although it was not purposeful.

  • 1

    I hope I have not conveyed the idea of being annoyed with the answer and the comments, but questions are to be clarified. And thank you all for understanding. + 1

  • 2

    "[...]creating some little monsters until I learn [...] " ... I saw myself in it! I made several of these that I couldn’t fix after... rsrs Great answer!

Show 5 more comments

13

Contextual introduction or TL; DR

This response is a democratic and healthy disagreement with the utluiz response. It is necessary to make this clear because some people think that diversity of vision is not constructive or even that it is a fight. I think here we’re doing it healthy and everyone can benefit from it.

Rather than a question that generates a good answer is to have a question that generates several good answers and that make people reflect and learn more, even if they disagree with what is written.

For someone who doesn’t have the patience to read everything or thinks they already know what they need to learn about it, what I say is,:

  • OOP is good, but it’s no panacea.
  • Everything utluiz says works well in other contexts, but in PHP much of the advantage of OOP is lost.
  • OOP brings new problems without solving all of the procedural, so some problems may benefit more from OOP or procedural, OOP is not suitable for anything.
  • I say that PHP usually meets problems more suitable for procedural than OOP.
  • Much of what is said in the other answer is about static typing, not OO.
  • The main disagreement is in using example of bad procedural against good OOP, is unfair!

His answer is not wrong, it has quality, I just want to give another view. In several parts, I agree with what is there. I just think it’s not really contextualized for PHP. PHP’s practice is a little different than what’s described there. The question is about OOP in PHP, not Java.

Some things in this answer make more sense by looking at the original version of his reply.

I strongly recommend watch a video which clearly shows how OOP is more problematic than it looks and where your problem really is. If you want to take the position that OOP is always great, okay, but don’t say I didn’t warn you :)

Best for libraries or complex systems

My opinion has always been (about 30 years) that OOP is best applied to libraries and Apis. Not only, of course, but mostly. And yet not in all library cases. For me OOP shines in problems where PHP does not usually pass close, but at specific points PHP can benefit from the paradigm.

Luckily people often think they are using OOP and are just using a simple class that works as a module or simple structure. The bad part is she got it right by coincidence. Using class does not mean you are doing OOP.

Consuming Apis that were built with OOP is not the same as object-oriented programming.

Abstraction and reuse

I agree that it is common to see people do everything the utluiz says in their response when they procedural program. But I’ve also seen people put everything into classes and make worse mistakes. See (right here on the site) most of the common codes that people write in OOP that make a much bigger mess than the one quoted. She piles up what she can’t and shreds what she can’t, it’s almost random.

Perhaps the explanation is correct if it is purely procedural in the way it was done in the 1960s/70s, but it is not the case to do so. Modularize is an important thing, make everything become an object not so much. I talk a lot about the subject in another question.

C is one of the few languages that do not implement any OOP facility and culture is not trying to force this paradigm into it. People program very well in it without this paradigm in the most complex systems possible and do not have the difficulties and errors cited (neither in the old version, nor in the new version of the utluiz response). The "problem" of language is to be very low level and what is most needed for it is generality and a little more modularization capacity. Okay, there’s also the culture of writing mnemonic code, but this has changed a lot. It remains to be more static than it is. In C and other languages you solve everything that was cited without difficulties.

There’s a specific kind of unquoted reuse in his answer that actually OOP helps, I won’t go into detail not to lengthen.

PHP is a very dynamic language And if you know what you’re doing, you get a lot of reuse without using OOP. In fact you can get even more by taking good advantage of the dynamic features of the language. Reinforcement that I’m not saying that OOP should never be used.

Abstraction is a good thing, and it’s been used since there was a computer, OOP didn’t invent this.

The problem is not the OO or procedural paradigm, or other, is not knowing how to use the tool. And some people sell OOP as if it’s something that you use and everything is solved. Even if it’s not their intention, they end up doing it without realizing it. Many people read that OOP organizes the code and it starts to adopt the paradigm as if it were magic. Who said maybe knows that it is not quite so, who reads and is still learning does not notice the nuances, does not understand that it is not panacea.

Example used

The problem of maintenance cited in this section of his answer occurs in the two paradigms. OOP has even a principle that says you should not modify your classes. Obviously you can not always follow this principle, changes cause difficulties in all paradigms.

The problem cited actually exists because of a language defect, so I quoted C that does not have this defect. PHP doesn’t really have a simple middle-term data structure. Or you have a array dynamic associative that produces the problem he cited or has the class that solves the specific problem. But this is a more static and dynamic thing problem, it is not a dichotomy between procedural and OOP.

Well, use the class then. Why did you put it in a class, are you doing OOP? So C is OO too, she has struct. Of course I disagree, everyone disagrees.

I will not repeat all the details of what I have already said in numerous answers, some quoted here, OOP is more than creating a class. Putting data into a structure I’ve always found useful, it’s using OOP like this?

enviar_email_cliente($JoseDaSilva); //esta variável é baseada em uma estrutura

You can do better than this, but I didn’t want to change the example that would be bad even in OOP.

There’s nothing oop in there. Whether this variable has a structure defined with AA or with class is not an important detail (internally in PHP it will give in PHP). Choose which one you think is best for your purpose, but the structure maintenance problem is solved. The examples cited create problem by doing it the wrong way.

Do you want the IDE to help? Ok, use the class to create the structure. Only the IDE will help because it has become more static and not because it did OOP.

Did you have the patience to get here? Then you’ll love it this blog that has a good article on this issue. Steve is the guy who can scare most readers away, but at least he doesn’t mess with superficiality, which I know people prefer. I don’t need to tell you that I’m a fan of his, even though I don’t agree with everything he says.

We’re creating a dichotomy between paradigms when actually the question is about typing. PHP would have much more robustness and maintenance facilities for having static typing than for using OOP. And if they take away the dynamic typing it loses its greatest merit. I have repeated several times that if it is to have all this robustness do not use PHP. Forcing the use of static typing and object orientation is misrepresenting what this language has always had good and different from other solutions. Having as an option for some things is very useful.

Call flow of functions

In the original answer there was something about this, see: /revisions/108209/1

I don’t see how the problem cited is solved by OOP. I actually think not only OOP, but all modularization helps to make the problem worse. Also I do not nail making "sausages" to avoid the cited problem, which is real.

It is possible to solve as well as OOP without using it, keeping a clean and organized syntax. If people don’t know how to do it is another problem, but they also don’t know what good is a builder, much used in OOP.

Global variables

Here is also about the original version

A real problem, but OOP doesn’t solve it, there are problems that need the global state.

The global variable has another problem: having global scope.

There are problems that either you complicate the design or does something that ultimately uses global scope, even if disguised. The problem with global scope is when it’s unnecessary and used anyway. There are problems that are inherently global.

In PHP even global abuse causes little problem because they are ephemeral. Of course it can cause some, but it can be a simple solution as well. And I’ll say it one more time, it can cause problems using any tool.

In another context I would find the global ones more dangerous.

I won’t dwell on it further:

Practical example

Based on the original utluiz response

I don’t like this example because it’s comparing a wrong implementation to a right one. Not one paradigm to another. The example shows how not to do procedural and how to do OO, is an unfair comparison.

But it’s not his fault to do this. It’s hard to give good simple examples that the paradigm itself clearly helps.

I understand that in OOP it is harder to make this mistake, but it is easier to make others, and even worse. Note that the difference of being more difficult and easier is derisory.

Example without class and without problems.

$time = Timer();
gerar_relatorio();
Stop($time);

Okay, you didn’t create a class and it all works out.

Has language that would allow to use $time->Stop(). That is the fault of the language and not of the paradigm. It is only syntax, does not change the semantics, does not change the paradigm.

There’s another example I can do without using a class that would do something similar. The syntax won’t look good in PHP, again it’s a language problem.

I solve this functionally better than procedural or OO, but functional is not fashionable, and is not welcome in PHP. In pseudocode:

Timer(gerar_relatorio, print) //é um exemplo, pode ser de outra forma, print é opcional

Anyway, Timer is it something from the application or library? This helps to substantiate what I said at the beginning. Nor do I think it is the case of Timer that can work well without OOP, but OOP is best applied to libraries, general or application-specific.

Use class Timer ready is programming OO or just consuming something that happened to be made like this?

That one Timer has to be well written in procedural or OOP, otherwise the comparison is not fair. If it needs to have more data, ok, create a data structure for it, but this is not OOP.

Possibly I would even use OOP to create a timer flexible. But in PHP 99% of the time people are not making libraries, or Erps, or dev tool, or other complex solutions "monolithic". PHP wheel scripts!

Encapsulation

The section cites global variables, but I didn’t see any in the code. I didn’t see a memory leak, I saw a poorly written code. And OOP doesn’t make people magically write code well written.

A person can know how to do good in OOP and bad in procedural. This can happen, there are people who only learned how to do it one way. There is little material teaching to do procedural right, the procedural legacy is really not good.

But what I see most (the reality of some privileged cannot be put to all) is that one does not know how to do both. This site has a good statistical universe to prove this. The procedural is simpler to learn.

Need to encapsulate? Okay, I’m always supportive, even though I’m not always as necessary as you think. Only encapsulate is not OOP, several paradigms preach it.

The mentioned incompatible changes occurred because the code was misspelled. If you misspell OOP the incompatibility will also occur. The answer states that the right thing to do encapsulation will solve a problem. Worth the same for the procedural, doing the correct has no problem at all.

The solution is given by doing it correctly and not because it used OOP or procedural. OOP does not help at this point, unless the person is used to OOP and has no idea how to do the same in procedural, there is an individual cultural issue.

To tell you the truth I thought the new version of the answer even tries to sell, even if it’s unintentional, OOP as a magic solution to all problems. There is a lot of rule to keep doing OOP to make everything work. So apply a lot of rule in Procedural and everything will be fine. It is very common for proponents to justify that OOP is not working because people do not know how to do it. Procedural also.

In a language of script the encapsulation is mainly by the containment of the code in source files that will be loaded on demand and that will be executed and then discarded. Want more granularity? You can, just know how to organize, as you also need to know in OOP.

I know it may be a simplification, but it seems that the answer sells a little the idea that OOP is encapsulating. It may not be intentional, I know. Encapsulation is part of several paradigms, OOP cannot take property for it.

In the process we can also change the internal structure without affecting consumers, just do it right. OOP also only delivers what he promises if he does it right.

I was going to do the procedural version of the new Timer OOP of the answer, but I found it so confusing that I decided not to risk :) I did not understand what the intention was there. It seems to me that OOP is bad too, but I may be mistaken for not having seen the whole context, it seems that the code mixes responsibilities.

Entities

I find it hardly relevant how the entity is represented. In PHP classes at the bottom are arrays associative, although the implementation differs somewhat from the standard AA of the language. In many situations it is not possible to determine whether everything in the class is being done correctly. The impression I get is that the answer does not consider the reality of PHP. To do everything she preaches PHP would have to have a more static form class than it is, you can’t guarantee what is not static.

Class creation can somewhat bureaucratize development, which is good in most applications made in Java, for example. But PHP is a language with less ceremony. I talk about it a lot in another question.

I admit that very disorganized people may find in OOP some salvation, but she may go wrong by opting for it. I see questions here on the site where the person started doing more procedural and she made mistakes, started doing OOP and got much worse. People are being "forced" to use OOP, no one wants to stay out of this that everyone is using.

Interestingly in OOP hour is preached to join everything, time is preached to separate. Yes, you have to do both, but that’s what I always say, using a general rule for specific cases doesn’t work. So much of what is said about OOP benefit doesn’t mean much when it comes to coding the real problem. It is beautiful in theory and bad in practice. Then who dominates the tool that is complex makes right, who does not dominate gets more confused.

Again, there are cases where there may be gains. The problem is that it is difficult to say without knowing the specific case deeply, thing that would take hours, days, can never be answered here.

Taking the specific example (from the original answer), who guarantees that the validation within the class will be called by itself or externally? Who guarantees that that validation can be used in all situations? Who guarantees that the system can work well with the object always in a unique valid state? I could continue asking several questions. OOP does not guarantee anything more, nor when well done, but the well done in any paradigm can give better guarantees in most situations.

Adding new fields is easier in a more dynamic structure than in a class, although in PHP the class can be streamlined.

All the problems cited can occur in any paradigm and no help do better what was poorly done.

OOP brings new problems, so they blew up the so-called Patterns design famous. Most of them were created to solve OOP problems, which do not exist if using "traditional" PHP. Apply procedural-specific standards and their problems will be solved.

I think if I had a canonical and popular book, maybe called "Design Patters to Procedural" :P and he had come before OOP, the latter would not have all this success. It’s quite a maybe, because the advent of GUI almost forced OOP to exist. And then you enter where OOP should be used, thing away from PHP. OOP makes more sense in JS than PHP.

Be careful not to confuse paradigms with design patterns, nor with typing.

Many of the advantages and disadvantages that people see in OOP (not all, of course) is more tied to language being static than being object-oriented. Interestingly pure OOP (that of Smalltalk) works best in dynamic languages, and does not give all the aforementioned guarantees. The problems cited do not exist in C which is procedural, but is static.

If PHP does not help to ensure much is a fallacy to say that something will be guaranteed if you use the paradigm. Again, the guarantee will come from the correct use of any paradigm, which is very subjective. Or static typing, which is something the class started to introduce in PHP. If it had been called struct and not class, would you accept that it is not OOP? I speak of the class as a container data, only, without other gadgets. The gadgets make it OOP.

The new version of the answer has new examples, but it is repetition of what I have already said, I will not comment specifically.

The potential of PHP in different paradigms

I agree with almost everything in this section, I make some reservations or rebounds.

PHP is often used for relatively trivial things. It is a language of script.

Imperative is different from procedural or functional, which are also different from each other. It is not only that one uses procedures and another uses functions, far from it define these paradigms (I will not go into detail, who has doubt, ask specific questions).

Imperative will not really disappear and it is totally orthogonal with several other paradigms, including OOP.

Procedural is also orthogonal, but not so much. The way to organize one or the other is different, at some specific point you choose one or the other, but can mix them in the application as a whole.

I see people actually having a lot of trouble with OOP, in all languages. OOP is not as simple as they sell. It is true that people also have problems with procedural, but it is because they have not learned to develop software in a general way and this, it seems to me, occurs more in PHP than other languages. I see even more in webdev in general, there seems to be greater "skydiving" in this area.

I agree 100% that procedural is easier and how it usually solves without any problem most of the problems that PHP usually works it should be the option default, at least for those who do not have OOP as their fundamental paradigm and who absolutely dominate it, which may even be a case of a golden hammer. Trying to do what you don’t understand is worse than doing it with the "best tool".

Listen to me! Prefer an axe to a chainsaw if you don’t know how to use one. Even if you don’t know how to use the axe either, and you have to cut down the tree anyway. Of course, I’d rather you learn to use both before you do this, but nobody listens to that. A well trained person on the axe will be very quick and will not hurt himself. On the chainsaw he will die before he can get proper training. I say this and people don’t listen. I see it all the time. And people who are well trained tend to encourage the subject to drop the axe and go to the chainsaw thinking that they’re going to magically train themselves, after all they managed to do this and they think that everybody can do the same. Well trained and on the right tree it is possible to benefit from the chainsaw. Although the risk will always be greater and when there is damage will also be. Of course I’m talking about procedural and OOP yet. It seems that loggers are smarter than programmers, they use both.

Lately I have noticed that those who learn OOP first, and even well, have difficulty understanding procedural correctly, maybe even because she has a vision of what OOP is, that, at the very least, I disagree.

Controversy

In the absolutely personal field then don’t take it as absolute truth.

I think many proponents of OOP must have read some book that sold OOP in a marketable way. This form puts OOP in such a generic way that its definition serves for a good part of the paradigms, that is, it talks about organizing code.

If so, then I’ve been programming OOP for over 30 years in everything I do, before I have any language mainstream supporting this "officially" and I have never heard of the term.

But I think OOP is much more than this, and the most of the OOP definitions found place requirements much higher than those cited generically. For me the generic definition of OOP is essentially the same as modularization. Which means she’s trying to "kidnap" something that’s not hers. As well as songs of questionable quality, such as "funk", "Sertanejo", and "pagode" that use names from other original and older musical genres, which had quality, to try to validate themselves.

OOP has no merit of its own?

Within the strictest specification I find OOP well valid for various problems. When it says that OOP is only a way of encapsulating, of putting things together, of separating responsibilities, reusing in general, of abstracting, for me is another paradigm. OOP cannot take what is present in other paradigms, not put anything else and say that it is something different. You can’t say that just putting the noun in front of the verb is an innovation that changes the paradigm. That’s just syntax, you can do this in procedural.

Ah, pure polymorphism does not give the expected robustness. It implemented in a static way it gives.

In questions quoted here I talk in more detail about what I and a lot of people see in OOP.

Do you disagree with that? Okay. I know there are two sides to what OOP is, I accept that. I hope that those who disagree will accept this too and not have their truth as absolute. You have questions on the subject, come on, disagree and substantiate what you think.

Completion

It’s everyone’s right to look for what they think is best for themselves. At no time do I say it’s wrong to use OOP, on the contrary, I use it.

  • Do what you dominate and feel more comfortable.
  • Start with the simple, and look for solutions to the problems when you realize they arise.
  • Don’t solve a problem that doesn’t exist.
  • Take it one step at a time.
  • Don’t force the use of a needless paradigm.
  • Understand what you’re doing, don’t follow recipes.
  • Don’t do it 'cause everybody’s doing it.
  • Ask yourself if you’re making the right decision. Question more experienced people with specific questions. Take advantage of their experience to accelerate yours, but don’t burn steps.

I think it’s fair that people want to evolve, master new tools, understand everything they can do. What I find strange is when one decides what is good for them without understanding how they use it right, and then ignores other ways that can be better. And give up evolving another way that might be better for her.

The biggest fallacy I see about OOP is that it organizes codes. It helps! How other things help. Who knows what he is doing will do well in any paradigm, who does not know will produce a disaster in any paradigm, but it will be easier to produce disasters in one that he does not dominate.

Today I see that the person does not learn the procedural well because there is no incentive to learn well and does not learn well OOP because it is harder to learn "right".

There is something that makes a difference using a food processor or a blender. There is something that gives in the same.

Why do people consciously prefer to use the knife if the processor is so good? Why use a razor blade if the machine is better? Why use the landline if the mobile solves everything? Why use other paradigms if OOP solves the problem better than them?

Apart from these frameworks complex - and I question quite the use of them in PHP - and some very specific cases, I rarely see valid use for OOP in PHP in the niche where it shines.

So below is an example of how I would apply OOP to a common PHP website:

 
 
 
 
 
 
 
 
 

:)

  • 3

    I miss the negative vote. + 1 to do justice. I agree with everything, except a few remarks I will make in my updated reply.

  • 3

    This last example was show hein kkk.. Thanks for the reply and the links, gave to substantiate a little more content. I personally use OOP only when I have a very massive code as a database, the rest I do without even using functions, because I really disagree with some things I’ve read, that say it’s better to use OOP in 100% of your project is organized and blab. I believe that it depends on the programmer to have an organized and adequate code and not a standard, etc. Thanks to the two who answered, both responses were good and complementary to the subject, thank you.

  • 4

    As no one who is negative is saying because it is clear that it can only be: A) the person does not understand the subject and thinks I am wrong, if she is sure I am wrong, she would speak where she is wrong; B) She just disagrees and thinks that the vote serves to demonstrate this; C) Just don’t like me and think I deserve punishment.

  • 1

    This time I was the one who disagreed, the edition you made and some other parts of it contradict much of what you wrote, various and sundry, and it makes unclear the purpose, and much of what you wrote seems like the diary of an enraged man, You yourself said that everyone should use the one that best dominates, many people agree, and it is known that a large part does not dominate OOP so much in PHP, au even in languages based on that paradigm. What has been said before is still valid, OOP is an advanced topic, people use it because they want to, not because they were forced to. ->

  • 1

    What ? <<frameworks>> ? These become practically part of a different chain, we just have to learn the methods and voilá built web/desktop applications without problems. Applications can still be made with normal PHP, or if we want something a little bigger, we take some advantage of what OOP has to offer. In several of my questions, you must have read a part where I said that "I’m not used to working with OOP much less frameworks ", And not really. I don’t know much, but I do manage with the paradigm, and I can say that I use OOP without problems when I need. ->

  • Newbies trying to create programs using advanced concepts when they barely master the basics of the language, it’s nothing new. The fact that OOP was sold to people ? I don’t disagree and I don’t agree, I’m half off. It’s well known that a lot of people use OOP because they think it helps solve a lot of the problems they encountered when they tried to program functionally, and OOP parameterizes the rest and throws the problem somewhere out of the programmer’s field of view or, even, the error is still there, and he barely notices the error and ignores, once again, It’s OOP’s fault ? ->

  • I repeatedly take advantage of OOP to solve problems I found when I used different approaches, both functional and prodecural, not that I did not know how to solve using any of the approaches previously experienced, but I ended up rewriting the application using OOP because of that particular problem. Why did I do that? Simple, I analyzed what other problems I would have if I continued to work in that way, compared in which case I would have more benefit and ready, besides foreseeing the same problem in different phases. ->

  • Solving problems without using OOP is quite easy, very even, but it’s not always the wonder as several people describe, it may be in most cases, but not at all. Programming with OOP has many advantages, but such advantages go unnoticed by amateurs - not everyone - and end up using OOP by "thinking things" and end up doing what they do. Generalizing the problem of misuse is not a solution. Some time ago I asked a question where MVC was a solution to several programming problems , and the question was considered non-constructive and closed. ->

  • I also remember that in one of my questions here at Sopt, about the use of the Patterns, you not only said that they are not a solution, but you should not make use of them. After a while I realized that Patterns are only tested practices and recommendations - great news -.-' - at that very moment I also realized that I used Patterns before. You said encapsulating is not just about OOP, as most people think, and you’re right about that, what about ** singletons**? They are exclusive to OOP ? You see the idea ?

  • Once again, I didn’t want to prove anything, just to say what I think and how I felt reading what you wrote. Just as many languages are chosen according to what they can provide more efficiently than others, I think PHP does well with the tasks that are assigned to it.

  • 2

    @Edilson ok, I respect your opinion. I disagree obviously. I agree that it may have been a little confusing because it has two versions of the utluiz response. What may seem contradictory is that I am not anti-OOP as some think. I show that he has problems, but it is not something horrible that should never be used. Being impartial is not easy. I know people want you to take sides. But I don’t do that. What you notice about what is written is your problem exclusively. I know what I feel. Thank you for justifying your vote, at least I know why it was given.

  • 2

    Clearly you have seen things in the text that do not exist, as you did with the text of utluiz, so it is not worth trying to debate point by point of your comments, will not lead anywhere. I find some conceptual errors in what you’re saying, and if I try this, it’s gonna get too long. You made a personal statement, it doesn’t mean it’s valid for other people. I don’t remember the question about Patterns, but I find it very unlikely that I have said what you are saying, I think I said something similar and you understood something else, it seems to be common that this happens.

  • I didn’t say what I said to debate, I just meant what I thought of your answer. "Clearly you’ve seen things in the text that don’t exist" - Unlike the previous answer, I had not read it before, but I read it from one end to the other. If you found errors or something like that is justifiable, but nothing has been invented. About the Patterns, what I meant is that they already existed, and people sometimes use Patterns even without knowing what they are, and they don’t always come as Patterns - this in the current context - although for the OOP these have gained more prominence due to the "mistakes" of the person.

  • Very good! Thanks for the other content, including the video!

Show 9 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.