Advantages of using object-oriented PHP? Where to use? [duplicate]

this question already has answers here : PHP mixes object orientation codes and procedural language? (2 responses) Closed 5 years ago.

Lately I've made a mini social media and I've hardly used object orientation, with the exception of a class I made for CRUD with PDO and GitHub ready libraries.

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

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

Author: Maniero, 2016-01-14

2 answers

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 the organization of the code, ease of maintenance and ability to extend the functionality.

Are you 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 it generates headaches to deal with the evolution of the code.

However, this paradigm alone does not solve any of the problems and, if misused, can cause as much or more harm than help.

You don't need Oo

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:

  • Data Structures basic: 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. They are a composition of organized code snippets (methods), which contains 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 data structure shared between them. Who knows how to program a little in C, for example, knows this 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 for nothing 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 SO about Oo advantages, an example being this question .

What distinguishes object orientation

A major differential of OO with respect to other paradigms is that it goes further in terms of data abstraction and encapsulation.

Of course, nothing is free. With the benefits come from 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 get slow or heavy just by using OO).

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

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

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

One might argue that just study the PHP API to learn how to use the functions, but in real projects you also need to learn the API of the particular system and other systems with which you integrate, sometimes more complex and disorganized than the language itself (if at all possible :P).

Given this chaotic scenario, the restrictions, standards and rules imposed by OO they 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 over time you will need to change the parameters. It is not uncommon in PHP codes out there to find functions with 10 parameters, some optional, others unnecessary. And if you need to remove a parameter, you'll have to exit by scanning the code looking for the call.

An alternative to this is to receive vectors, maps, or other generic structures as parameters. This can 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 which are mandatory and the rest optional.

A 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 large ERP, composed of modules developed by different teams, and there are hundreds of calls to the routine and in none of them the values are static as in the example.

Now imagine that it was necessary to remove the attribute endereco from 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 will the IDE or interpreter warn you that the attribute no longer exists?

This is a trade-off between flexibility and security. Too much flexibility, as is 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 incur the great risk that one snippet of code will inadvertently interfere with others.

Let's go to 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 it is not known on which planet we are 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 has been found that the process is leaking a lot of memory and one wants to investigate when this occurs. For this we need to recover the amount of memory allocated before running the routine and amount of memory after it runs and adds This information to a log file.

How can we change the routines to do this 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 do not want global variables, we can change the return of the routine inicar_timer to return an array containing both the time and the memory and thus retrieve both values in finalizar_timer.

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

One might argue that it is possible to fix this in a simple way. 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 to world because once again changes incompatible with previous versions have been implemented and now everyone will have to stay using an old version of their code or stop what they are doing looking for all the uses of the affected routines, adjusting and testing everything again.

OO does not solve all the problems, but in this example (and in several others that I see in the day to day) a correct encapsulation of the state could have solved the whole start problem. On the other hand, the lack of encapsulation, tends to cause 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: Oo restrictions increase reuse because they limit how client code can interact with data.

In functional programming, on the other hand, we could still have a method that does the counting automatically. 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 make an object available 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 get a more flexible, secure, and consistent API. we can change the internal implementation without affecting who uses it a routine .

Entities

You should probably have some entities that you save in a database.

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

For example:

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

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

Now with 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 the i shopping cart. Let's calculate the total:

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

If there are multiple locations in your application where you need to scroll, add, remove, search elements and so on, you have basically two options. One is to access everything manually as in the example above, and when changes occur (such as new fields), you leave 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 this all 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 doing manually what we could delegate to the PHP interpreter do more securely.

Going further, but let's imagine that now you have carts with many items and often need to scroll 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 don't All Access via functions own.

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

Again:

  • lack of encapsulation is a common source of problems.
  • is complicated to maintain consistency by 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 not clear how they can or can't use their data structure, whereas with classes this would be more obvious.

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

Using the validation example, a well-encapsulated object ensures 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 to prevent having to analyze in each routine the entire structure received to determine if the state is valid. This leads to many libraries not performing sufficient validation, resulting in difficulties in identifying problems when unexpected values appear.

The potential of PHP in different paradigms

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

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 leverage to some extent. Even languages such as Java, traditionally not friendly to this paradigm, embraced it vehemently in its version 8.

Already procedural programming is something that, to some extent, inevitable. We are not yet at the stage (and I'm not sure we will get there) where everything can be solved by functional expressions. Good old control structures such as if and for will still exist within methods and functions.

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

The language is well known for being easy to learn, where someone you can have some code running successfully on your first day, if not 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, besides that PHP has a very strong procedural inheritance and practically all modules have a procedural API, sometimes supporting OO at the same time or mixing objects with isolated functions.

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

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

Examples where object orientation is bad

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

  • templates , for example, like Wordpress HTML templates where you mix control logic with HTML code. Even in other languages this holds. Although helper objects ( helpers ) are used, a text template is inherently procedural in its nature.
  • stateless functions (stateless ) does not store or share variables, nor do they have any prerequisites. For example, even in a purely OO language, a routine for converting an integer to text does not necessarily have to be in an object. Or Java, by example, uses static method for such cases.
  • high-performance routines work best with simple data structures.

Project patterns

Several open source projects die of lack of maintenance due to poor structuring, as no one can or has the courage to mess around. Regardless of the paradigm used, it is important to learn best practices.

Design Patterns are not exclusivity of the OO programming, but they are known solutions to specific problems, as well as a common language for you not to reinvent the wheel and call it a "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:

  • the good thing is that you will learn other ways of thinking about the problem that you would not have done on your own and will soon be adjusting and composing these different patterns into new forms. So you use the experience of others to grow faster.
  • the bad thing is that you start wanting to apply the standards in 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 it aims for reuse and communication between different parts of the code at the same time that it aims for certain encapsulation to avoid problems further down the line.

Use the paradigm that is best to solve every problem, including all together. But for this you will need to know everyone, in addition to the good and bad practices of each.

 17
Author: utluiz, 2017-04-13 12:59:44

Contextual introduction or TL; DR

This answer is a democratic and healthy disagreement with utluiz's answer. It is necessary to make this clear because some people think that diversity of vision is not constructive or even that it is quarrel. I think here we are doing it in a healthy way and everyone can benefit from it.

Better 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 those who do not have the patience to read everything or think they already know what they need to learn about it, what I say is:

  • OOP is good, but it is not a 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 state that PHP usually addresses problems more suited to procedural than OOP.
  • much of what is said in the other answer is about static typing, and not Oo .
  • the main disagreement is in using bad procedural example against good oop , it's 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 don't think she it's well contextualized for PHP. The practice of PHP is a little different from what is 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 answer.

I strongly recommend watch a video that clearly shows how OOP is more problematic than it sounds and where your problem really is. If you want to stick with the position that OOP is great always, ok, but don't say that did not warn:)

Best for libraries or complex systems

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

Luckily a person often thinks they are using OOP and are only using one class simple that works as a module or a simple structure. The bad part is that 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 utluiz says in their answer when programming procedural. But I've also seen people put everything in 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 cited. She piles up what she can't and shreds up what she doesn't give, it's almost random.

Maybe the explanation is right if you do purely procedural the way you did in the 60s / 70s, but it is not the case to do so. Modularize is something important, make everything turn object not so much. I talk a lot about it in other question .

C is one of the few languages that does not implement any oop facility and the culture is not trying to force this paradigm into it. People Program very well in it without this paradigm in the most complex possible systems and do not have the difficulties and errors mentioned (neither in the old version, nor in the new version of the utluiz answer). The" problem " of the language is to be very low level and what it needs most is generacity and a little more ability to modularization. Yeah, there's also the culture of writing pneumonic code, but that's changed a lot. It needs to be more static than it is. In C and other languages you solve everything that was cited without difficulties.

Has a specific type of reuse not mentioned in his answer that really oop helps, I will not go into detail not to stretch.

PHP is a very dynamic language and if the person knows what he is doing can get a lot of Reuse without using OOP. In truth can get even more by taking good advantage of the language's dynamic features. Reinforcement that I'm not saying that OOP should never be used.

Abstraction is a good thing, and it is used since there is computer, OOP did not invent this.

The problem is not the oo or procedural paradigm, or other, it is not knowing how to use the tool. And some people sell OOP as if it's something you use and everything settles. 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 goes on to adopt the paradigm as if it were magical. Those who said it may know that it is not quite so, those who read and are still learning do not perceive the nuances, do not understand that it is not a panacea.

Example used

The maintenance problem cited in this section of his answer occurs in both paradigms. OOP even has 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 cited C that does not have this defect. Really PHP does not have a simple data structure half-way. Either you have a dynamic associative array that produces the problem it cited, or you have the class that solves the specific problem. But this is a problem of more static and more dynamic thing, it is not a dichotomy between procedural and OOP .

Well, use the class then. why did you put in a class, are you doing OOP? So C is OO too, it has struct. Of course I disagree with this, 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 in a structure I've always found useful, is it using OOP like that?

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

Can do better than this, but I didn't want to modify the example that would be bad even in OOP.

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

Want IDE to help? Ok, use the class to create the structure. Only the IDE will help because it became more static and not because he did OOP.

Did you have the patience to get here? Then you will love this blog that has a good article on this question . Steve is the guy who can amaze most readers, but at least he doesn't create confusion with superficialisms, which I know people prefer. I don't need to say I'm a fan of him even though I don't agree with everything he talks about.

We are creating a dichotomy between paradigms when in fact the question is about typing. PHP would have much more robustness and ease of maintenance by having static typing than by using OOP. And if you take away dynamic typing, it loses its greatest merit. I have repeated several times that if it is to have this robustness all do not use PHP. forcing the use of static typing and object orientation is to misrepresent what this language has always had good and different from other solutions . Having as an option for some things is quite useful.

Function call flow

In the answer original there was something about this, see: https://pt.stackoverflow.com/revisions/108209/1

I don't see how the problem cited is solved by OOP. In fact I think not only OOP, but all modularization helps to make the problem worse. Also do not nail do "tongues" to avoid the mentioned problem, which is real.

It is possible to solve as well as OOP without using it, while maintaining a clean and organized syntax. If people don't know how to do it is another problem, but they also don't know what a Constructor is for, much used in OOP.

Global variables

Here is also about the original version

A real problem, but OOP does not 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 do something that basically uses global scope, even if disguised. We global scope problem is when it is unnecessary and is used just like that. There are problems that are inherently global.

In PHP even the abuse of globals causes little problem because they are ephemeral. Of course it can cause some, but it can be a simple solution as well. And I will repeat once again, it can cause problems using any tool.

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

I will not stretch, more about the Subject:

Practical example

Based on utluiz's original answer

I don't like this example because it's comparison of a wrong implementation with a right one. Not from one paradigm to another. The example shows how not to do procedurally and how doing OO, it's an unfair comparison.

But it's not his fault to do this. It is difficult 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 between being harder and easier is derisory.

Example without class and without problems.

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

Okay, you didn't create a class and everything works out.

Has language that would allow use $time->Stop(). There is a defect of the language and not of the paradigm. It's just syntax, it doesn't change semantics, it doesn't change the paradigm.

Has another example I can do without using class that would do something similar. The syntax will not look good in PHP, again it is a problem of the language.

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

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

Using Class Timer ready is programming OO or just consuming something that happened to be done like this?

This 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 it's not OOP.

Possibly I would even use OOP to create a flexible timer. But in PHP 99% of the time people are not making libraries, or ERPs, or dev tool, or other complex "monolithic"solutions. PHP runs 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 codes well write.

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

But what I see most (the reality of some privileged can not be put to everyone) is the person not knowing how to do both ways. This site has a good statistical universe to prove this. The procedural is simpler from it learn.

Need to encapsulate? Okay, I'm always supportive, even though it's not always as necessary as you think. Just encapsulating is not OOP, several paradigms preach this.

The incompatible changes cited occurred because the code was poorly written. If you misspell OOP the incompatibility will also occur. The answer cites that the correct encapsulation will solve a problem. The same goes for the procedural, doing the right thing has no problem at all.

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

To tell the truth I found that the new version of the answer even tries to sell, even if it is unintentional, OOP as a magic solution to all problems. It has a lot of rule to follow doing OOP to everything go right. Then apply a lot of rule in procedural and everything will work out. it is very common for proponents to justify that OOP is not working because people do not know how to do it right. Procedural also .

In a language of script encapsulation occurs mainly by containing the code in source files that will be loaded on demand and that will then execute and be discarded. Want more granularity? It has how, just know how to organize, as it is also necessary know in OOP.

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

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

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

Entities

I find it irrelevant how the entity is represented. In PHP classes in the background are arrays associative, although the implementation differs somewhat from the standard AA language. In various situations it is not possible determine if everything in the class is being done correctly. The impression I have is that the answer does not consider the reality of PHP. To do everything it preaches PHP would have to have a class more static than it is, you can't guarantee what is not static.

Creating classes can bureaucratize development a bit , which is good in much of applications made in Java, for example. But PHP is a language with less ceremony . I talk a lot about this in another question.

I admit that very disorganized people can find in OOP some salvation, but she can give herself wrong by opting for it. I see questions here on the site where the person started doing more procedural and she erred, went on to do 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 folds to join everything, time bends 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's going to encode the actual problem. It looks beautiful in theory and lousy in practice. Then those who master the tool that is complex do it right, those who do not master it gets in the way more.

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 single valid state? I could keep asking several questions. OOP does not guarantee anything more, nor when well done, but 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 dynamized.

All the problems mentioned can occur in any paradigm and no help doing better what was done wrong.

OOP brings new problems , so exploded The such of design patterns famous. Most of them were created to solve OOP problems, which do not exist if you use "traditional"PHP. Apply specific standards to the procedural and its problems will be solved.

I think if I had a canonical and popular book, maybe called "Design Patters for Procedural " : P and he had come before OOP, the latter would not have this whole success. It's quite a maybe, because the advent of the GUI almost forced OOP to exist. And there it comes where OOP should be used even, thing far from PHP. OOP makes more sense in JS than PHP .

Be careful not to confuse paradigms with design patterns or typing.

Many of the advantages and disadvantages that people see in OOP (not all of them, of course) is more tied to the language being static than being Object-Oriented. Interestingly pure OOP (that of Smalltalk) works best in dynamic languages, and does not give all the guarantees mentioned. Problem quoted does not exist in C which is procedural, but is static.

If PHP doesn't help guarantee much it 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 introducing in PHP. If it had been called struct and not class, would they accept that it is not OOP? I speak of the class as a container of data, only, without others paraphernalia. The paraphernalia 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 caveats or remarks.

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

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, anyone in doubt, ask specific questions).

Imperative really won't go away and is fully 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 a specific point you choose one or the other, but you 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 even see more in webdev in general, there seems to be greater "skydiving" in this area.

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

Listen to me! Prefer an ax than a chainsaw if you don't know how to use one. Even if not know how to use the ax too, and either way you have to cut the tree. Of course I'd rather you learn to use both before you do this, but no one listens to this. A well-trained person on the ax will be quite fast and will not get hurt. On the chainsaw she will die before getting proper training. I speak this and people don't listen. I see this all the time. And people who are well trained often encourage the subject to drop the axe and go for the chainsaw thinking they will magically self-train, after all they managed to do this and think that everyone 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 higher and when erar the damage will also be. Of course I'm talking about procedural and oop yet. It seems that Lumberjacks are smarter than programmers, they use both.

Lately I have realized that those who learn OOP first, and even well, have difficulty understanding procedural correctly, perhaps even because she has a view of what OOP is, which, at the very least, I disagree with.

Controversy

In the absolutely personal field so don't take this 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 a good part of the paradigms, that is, it talks about organizing code.

If that's it, then I I program OOP for over 30 years on everything I do, before I had some mainstream language supporting it "officially" and I have never heard of the term.

But I think OOP is much more than that, and the majority of definitions about OOP found place much greater requirements than those generically cited. For me the generic definition of OOP is essentially the same as modularization. That is, she tries to "kidnap" something that is not hers. So as songs of questionable quality ,such as" funk"," sertanejo", and" pagoda " that use names from other original and older musical genres, which had quality, to try to validate themselves.

Oop has no merits of its own?

Within the strictest specification I find oop well valid for various problems. When it is said that OOP is only a way to encapsulate, to put things together, to separate responsibilities, to reuse in a general way, to abstract, for me it is another paradigm. OOP can not take what is present in other paradigms, put nothing else and say that it is something different. It cannot be said that just putting the noun in front of the verb is a paradigm-changing innovation. That's just syntax, you can do this in procedural.

Oh, pure polymorphism does not give the robustness expected. It implemented statically is that gives.

In questions cited here I talk in more detail about what I and many people see in OOP.

Do you disagree with this? Alright. I know there are two strands of what OOP is, I accept this. I hope that those who disagree accept this too and do not have its truth as absolute. You have questions on the subject, come on, disagree and substantiate what you think.

Conclusion

It is everyone's right to look for what they think is best for themselves, I just wanted to put another perspective. At no time do I say that it is wrong to use OOP, on the contrary, I use it.

  • do the that you master and feel more comfortable.
  • start with the simple, and go looking for solutions to problems when you realize they arise.
  • do not solve a problem that does not exist.
  • Take one step at a time.
  • do not force the use of a paradigm without need.
  • understand what you're doing, don't follow recipes.
  • Don't do it because everyone is doing.
  • whether the decision is being made right. Question more experienced people with specific questions. Take advantage of their experience to speed up yours, but don't burn steps.

I think it's fair for a person to want to evolve, to master new tools, to understand everything they can do. What I find strange is when the person decides what is good for him without understanding how he uses that right, and goes to ignore other ways that may be better. And give up evolving in another way that may be better for they.

The biggest fallacy I see about OOP is that this organizes codes. He 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 master.

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

Has Thing that makes a difference using a food processor or a blender. There's something about it anyway.

Why do you have people who consciously prefer to use the knife if the processor is so good? Why use 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 they do?

Outside of these complex frameworks - and I question quite a lot the use of them in PHP - and some well specific cases, I rarely see valid use for oop in PHP in the niche where it shines.

So below I give an example of how I would apply OOP on a common website in PHP:

 
 
 
 
 
 
 
 
 

:)

 13
Author: Maniero, 2020-06-11 14:45:34