📜 ⬆️ ⬇️

PHP: the wrong way

image

In the world of PHP programming, there is a set of trends. Some people actively promote them (in books and on websites) as “modern PHP”, while others put them as outdated, stupid, or simply wrong.

It seems that all these people tirelessly try to get everyone to program as they see fit. This article is written to share a pragmatic view of PHP programming. A look dictated by experience and practical implications, not popular trends, theories or academic dogmas. The material presented on the PHP site - The Wrong Way will be updated as new information becomes available. We invite everyone to participate in this.

Danger of extremism


There are one problem with the rules and programming guidelines: they often make sense only in specific conditions. If you go beyond these conditions, a good rule turns into a terrible. In fact, any good rule, taken to the extreme, becomes bad.
')
It is important to understand this, because programming extremists often misused many of the principles and rules of software development that appeared from time to time and were offered by different people.

Experience suggests that the misuse of basic guidelines and rules always complicates projects, reduces their safety and leads to erroneous and sometimes disastrous results.

The KISS principle , which some decode as "Keep It Simple, Stupid", is extremely wise and correct, experienced people urge to follow it. But even KISS can be a threat to the project, if you bring it to the point of absurdity. There is such a thing as excessive simplicity, which in our case leads to a lack of functionality.

Wrong way: religious adherence to rules and guidelines.

Permanent use of frameworks


All general purpose PHP frameworks suck!
Rasmus Lerdorf

In the PHP community, the really bad trend has become a de facto standard when developing web applications. It is about using popular general purpose frameworks.

This phenomenon is widespread. The reason for this is not the improvement of the development results and the incorrect execution of any operations in terms of technology and architecture. It's just that some authors of the frameworks have taken the developer community with the help of polemic against creating applications from scratch. The characteristic slogans are "Do not reinvent the wheel!" And "Do not do everything yourself, more experienced people have already taken care of this."

Many of the modern programmers completely ignore the fundamental principles of normal programming and spend a lot of time fantasizing about new layers and levels of difficulty in order to become smarter and cooler than those whom they consider to be their peers.

These people are so fond of enthralling others, becoming peculiar opinion leaders in the PHP community, convincing everyone to use fresh and "fashionable" open source tools, that they forget to make sure of the meaningfulness and sense of their advice. A general purpose framework can be compared to a house assembled in a factory. Building an application using such a framework will make you a coder or a programmer to the same extent as building pre-assembled houses will turn you into a carpenter.

In this article, we distinguish between frameworks and libraries by the following features:


In the world of Python and Ruby, creating websites from scratch is quite a tedious task, since these languages ​​were not meant for creating websites. As a result, general-purpose frameworks such as Django and Ruby on Rails quickly became popular specifically for website building in Python and Ruby.

And PHP Rasmus Lerdorf initially created as a set of tools written in C, allowing you to easily and quickly develop dynamic HTML. PHP was thought of this way and remained so, he himself is a framework .

Throughout its existence, PHP has been actively developing, and today it can be used for much more diverse tasks than building HTML and websites. But it's wrong to treat PHP as a framework. By its nature, it is a level of abstraction for developing web applications, which is entirely written in procedural C.

Using libraries in projects is completely natural. PHP comes with a set of libraries that can extend your code. For example, PDO is a small library that provides a consistent interface for accessing databases in PHP.

But using the framework on top of PHP is another matter.

In this case, you add the level of abstraction on top of another level of abstraction, which was originally created as a base point of reference. The added level provided by the framework can simply organize your code into pre-built template sets. Or it can increase the complexity by interweaving hundreds or thousands of classes and methods into the hellish mess of dependencies. But in any case, you add to the code a new level of complexity, which is absolutely not needed!

Gaining experience begins with the interface. The interface is the result of basic technologies and a certain number of levels of abstraction. The more abstractions you use, the less efficient the interface becomes, the more errors you put into the application. The higher the abstraction, the more detail and efficiency you lose.

Clearly understand: the lines of code in any project should be as small as possible in order for the code to become as clean and readable as possible!

People don't need general purpose frameworks. No one has common problems, everyone is trying to solve very specific problems.
Rasmus Lerdorf

Some companies, too, are filled with fuss around PHP frameworks and begin to use them in their projects, which results in a catastrophe. Companies are faced with the fact that general purpose frameworks do not help to solve specific tasks, and they are also very slow in their work. The frameworks cannot be scaled, and many companies are trying to tear out pieces of them in desperate hope of getting work that was not required initially.

Always use a pragmatic approach in which:

Action or policy is dictated by consideration of direct practical consequences, and not by theory or dogma.
Collins English Dictionary, full version, 12th edition, 2014

Wrong way: always use the framework on top of PHP.

Continuous use of design patterns


I have a strong allergy to projects and design patterns divorced from life. Peter Norvig has written a good article that design patterns are just flaws in your programming language. Switch to a better language. And he is absolutely right. Everyone worships patterns and only think: “Aha, I will use the pattern X”.
Brendan Aich. Coders at work - Reflections on the Craft of Programming

Design patterns are reusable solutions to frequently encountered problems in an application architecture. Templates are not a complete project that can be directly converted to code. This is just a description, an idea of ​​how to solve a problem, for use in many different situations. Object-oriented patterns typically demonstrate connections and interactions between classes or objects without defining the final classes or objects of the application.

PHP supports imperative, object-oriented, procedural, and reflective paradigms. PHP is a huge toolbox that allows you to solve various tasks in a variety of ways, not just one. PHP is a freedom, fast and scalable solution.

Trying to improve ourselves and in particular our code, we sometimes focus on the philosophy of specific patterns or ideas, while forgetting to think practical.

When I see patterns in my program, for me this is a signal of trouble. The program structure should reflect only the problem being solved. Any other patterns in the code say (at least to me) that I use insufficiently strong abstractions. For example, that I manually generate macro extensions to write.
Paul graham

You cannot fall into the trap of philosophy or the idea behind a particular template or solution. Our main task is to make the code as easy as possible to understand, and therefore safe and easy to maintain.

Also, do not forget about the existence of anti-patterns. These templates can often be used, but they are ineffective or even counterproductive.

I think initially the templates were some recognizable best solutions to frequent problems. But after a while we found that applications became ten times harder than necessary, because people are trying to push all the templates they read about there (“My application is well thought out, because the templates are loaded with templates”). So my idea of ​​the value of patterns has changed.
Paul Wheaton. Evil Design Patterns

Always use a pragmatic approach in which:

Action or policy is dictated by consideration of direct practical consequences, and not by theory or dogma.
Collins English Dictionary, full version, 12th edition, 2014

Wrong way: look for a template to solve the problem.

Constant use of object oriented programming


The problem with OO languages ​​is that they drag all of their implicit environments. You wanted a banana, but you got a gorilla that holds a banana, and all the jungle to boot.
Joe Armstrong. Coders at work. Reflections on the craft of programming

Abstraction is power. And what really disgusts me and what I talked about back in the 1990s is CORBA, COM, DCOM, object-oriented crap. At that time, every startup offered some crazy thing that when launched caused 200 thousand methods and output “Hello world”. This is a parody! You, as programmers, do not need to associate yourself with such things.
Brendan Aich. Coders at work. Reflections on the craft of programming

Many developers and companies today believe that OOP is the only viable way to develop. And those who argue with this immediately realize that they are going against the "generally accepted opinion" of the industry.

Programming blogs and forums are full of defenders of the PLO, confident that they understand what they are talking about, although there is no standard definition.

But the fact is that the so-called object-oriented programming is very often too complicated!

We, computer scientists and programmers, should put aside prejudice and look for the best solution for a specific problem.

Today, one of the main advantages of PHP is the support of imperative, functional, object-oriented, procedural and reflective paradigms. PHP is a huge toolbox that allows you to solve various tasks in a variety of ways, not just one .

When we try to solve various problems within an application using one specific programming paradigm, we cease to think creatively and work efficiently.

Little historical lesson


One of the best ways to understand the programming paradigm is to see how it originated. What is the reason? What problems in other paradigms needed a new approach? Was the problem practical or academic? And how much time has passed since the creation of the paradigm?

It doesn’t matter what person X says or what definition Y person gives. The historical background of paradigms is important.

There are two ways to develop an application architecture. The first is to make it so simple that obviously there are no flaws. The second is to make it so difficult that there are no obvious flaws.
Charles Anthony Richard Hoare

Previously, before the advent of the PLO, around the end of the 1950s, languages ​​were used to create many programs with an emphasis on unstructured programming. They are sometimes called first and second generation languages. Unstructured programming historically became the first paradigm. She was actively criticized for spaghetti code.

There are both high- and low-level languages ​​using unstructured programming. For example, BASIC, COBOL, MUMPS, JOSS, FOCAL, TELCOMP, machine code, early assembler systems (without procedural metaoperators), a number of scripting languages. A program in an unstructured language usually consists of consecutive commands or expressions, usually one per line. Strings are either numbered or may contain labels that allow the thread to go to any of the lines (such as the unpopular GOTO expression). In the 1960s, structured programming emerged, thanks in large part to the famous letter from Edsger Dijkstra.

Structural programming is a paradigm that improves the purity, quality, and development process using subroutines, block structures, and cycles. This is in contrast to simply jumping over the expression GOTO.

Then procedural arose from structured programming. It is based on the concept of a “procedure call”. This is another name for the "function call". Procedures are also known to you as subroutines or methods. In essence, this is a series of calculations that need to be performed. Any procedure may be caused by other procedures or independently at any time during the execution of the program.

At first, all procedures were available in any part of the program as global data. In small programs, this is not a problem, but as programs become more complex and small, small changes in one part began to strongly influence many other parts. One small change to the procedure could lead to a cascade of errors in a bunch of other procedures depending on it.

There was a new technique that allows you to divide the data into different areas of visibility: "objects". Only the specific procedures belonging to the same scope could access the same data. This is called data hiding, or encapsulation. As a result, we managed to organize codes much better.

Initially, objects were not called objects, they were simply considered as separate areas. Later, when the dependencies and relationships between variables within these areas decreased, they were considered as isolated segments, and eventually the concepts of "objects" and "object-oriented programming" emerged.

Then, mainly because of the advent of Java, new fashionable terms appeared, and the “procedure” or “function” was renamed “method” when it belongs to a separate scope. Variables are renamed “attributes” when they belong to a separate scope.

So an object, in essence, is simply a set of functions and variables, which are now called methods and attributes.

Methods and attributes are isolated within a separate scope with a “class”. And when an instance of a class is created, it is called an object.

Objects can refer to each other, and thanks to this, the methods (functions) inside them also “interact” with each other. Objects can also "inherit" methods from other objects, thereby expanding them; this is called "inheritance". This is a code reuse method that allows you to create independent extensions of applications through public classes and interfaces. Relationships between objects gave rise to a hierarchy. Inheritance was created in 1967 for the language Simula 67 .

Objects can also inherit methods from other objects and "redefine" them with additional or modified functionality, this is called "polymorphism".

In different languages, these ideas are implemented very differently.

Object-oriented programming is another way of organizing code. This is an extension of procedural programming associated with data hiding (encapsulation) and the avoidance of global scopes. This extension of functions by “borrowing” their drawings without affecting the original code (inheritance). And this is a redefinition of functions without affecting the original code (polymorphism).

Model OOP allows you to easily create programs by accretion (capacity). In practice, this often means that it is a structured way of writing spaghetti code.
Paul Graham. Ansi Common Lisp

Wrong way: always use object-oriented programming.

Fear someone else's code


One of the frequent arguments justifying the use of frameworks is the unwillingness of people to deal with code bases made from code fragments written by others.

This rather strange thinking, mostly characteristic of web developers, speaks of a lack of professionalism and experience.

It is perfectly normal to create an application and work with code written by others. This is part of the daily work of a professional programmer, and do not need to be afraid of it.

A professional will not whine that his work is now completely dependent on the code of the employee, who probably no longer relates to the company or project, but if this employee used framework A or framework B, then it would save you a day of work.

Professionals do not think so. No one.

Perhaps its role in the prevalence of such thinking plays a low threshold for entering a web development in PHP. But in any case, this suggests that a person is on the wrong path.

Programming largely involves interacting with people using someone else's code. This is part of the job: trying to improve the existing code base, and sometimes you have to completely rewrite it. Read what the programming masters say in Coders at work. Reflections on the craft of programming .

Some of the largest and most successful code bases in the world have been developed by hundreds of people who have never met each other. These databases are created without the use of frameworks, exclusively in procedural programming languages ​​using only the procedural paradigm. And no one even dreamed of doing it differently.

The Linux kernel contains over 20 million lines of code written exclusively with procedural programming. In its creation involved 14 thousand people - and no frameworks. The various BSD features and most of the Linux GNU userland are also written only through procedural programming without the use of frameworks.

The same can be said about the hundreds of open source projects around the world abandoned by the authors just to be picked up by other experienced programmers. For many of these projects there is very little documentation (or there is none at all), there are no comments in the code, no guidelines or other types of assistance.

What is really there - the entire PHP codebase is written in C, a procedural language, without frameworks.

When you define a class in PHP or when you run your favorite PHP framework, you do someone's procedural work!

Of course, there is a terrible code, which, probably, was not originally designed in any way or that has grown many times, but the client did not want to rewrite it. The codebase is so terrible that you cannot find the ends. But no framework will protect you from this situation. Often this is the stage of normal growth of the program. In the end, any framework will simply break into pieces.

Of course, there is a horrible spaghetti code, but no one deliberately writes it. Sometimes this is the result of lack of experience, often - the fault of customers, many times changing the specifications in the midst of development. But in both cases, you would still get a spaghetti code, even when using the framework. And no matter how intensively you begin to apply the object-oriented paradigm: the result will be the same.

As programmers, we must prevent such situations, but this is normal , this is the art of programming , this is part of what is called being a programmer !

Wrong way: fear code written by others.

Follow PHP-FIG Standards


FIG stands for Framework Interoperability Group (Framework Compatibility Group).

PHP-FIG was created by framework developers at the php | tek conference in 2009. Since then, its membership has increased from 5 to 20 participants.

There are a lot of controversies with PHP-FIG. Some people consider this the best undertaking of the PHP community since the birth of PHP itself. Others are sure that it is worth forgeting about the existence of this group as soon as possible.

One of the problems is how PHP-FIG positions itself in its FAQ :

The task of our group is to give participants the opportunity to talk about the commonality between our projects and try to find ways to work together. Our audience is ourselves, but we understand perfectly well that the rest of the PHP community is watching us. We will be happy if others want to accept what we are doing, but this is not an end in itself. No one in our group tells you how to create applications.

However, if we look at the work of several group members, it becomes obvious that the real goal completely contradicts the stated one. The group is trying hard to turn the PHP-FIG into a “group of PHP standards,” which was their original name . In the books of the group members, on their websites, in blogs, on forums, etc., the work of PHP-FIG is called modern PHP, and all other approaches are declared obsolete.

The problem with PHP-FIG is that, although many frameworks and open source projects have implemented a number of group standards, these standards themselves are mainly designed to solve problems “in terms of the framework,” which makes them useless in many practical situations.

Quite a few developers create software that must be extremely effective, safe, and profitable in order to be bought and used. They can not be distracted by standards that must meet the needs of framework fanatics. It will be a disaster for business.

If any group is needed, its standards should reflect the interests of the entire PHP community, and not just the framework developers and open source CMS projects. Such a group should represent the developers of the PHP language itself, with a much larger number of participants, and with the right to vote.

If you decide to follow the PHP-FIG standards, you should understand that some of them - for example, the PSR-0 and PSR-4 autoloader standards and a number of others - directly affect how you write software code.

In many areas, highly scalable, time-critical, cost-effective software is required, which is simply impossible to create if you follow the PHP-FIG standards.

Wrong way: follow the PHP-FIG standards, except PSR-1 and PSR-2.

Security neglect


There is one problem with programmers: you never know what a programmer does until it is too late.
Seymour Cray. defprogramming.com

Secure code is a way of writing programs that are resistant to attacks by attackers and amused, as well as other programs. Secure code protects data from being stolen or damaged. Insecure code can give attackers control over the server or user credentials. Consequences - any, up to the exit of service from the system and hacking of the systems of thousands of users

Each program is a potential target for attack. Forwards will try to find vulnerabilities in your applications and use them to steal important information, violate the integrity of programs and data, and gain control over servers and networks. At stake is your customers' property and your reputation.

You can not just add security to the application!

To make an insecure application safe, you may have to significantly redesign it. You must determine the origin of threats to your software and implement secure code techniques from the very beginning, sticking to them throughout the planning and development of the application.

Security of critical software resources is more important today than ever, since the main vector of attacks is constantly moving to the application level. According to a 2009 SANS study, attacks against web applications accounted for more than 60% of all attacks registered on the Internet.

A special feature of PHP is that it is both a programming language and a web framework. There are a lot of web functions built into the language that make it very easy to write unsafe code.

Default security


The complexity is killing. It sucks the life out of developers, makes it difficult to plan products, create and test them, confronts us with security challenges and tires upon end users and administrators.
Ray ozzie

To develop applications with the implementation of the correct security requirements, it is necessary to use safe code writing techniques and pay attention to the risks in daily operations, your thoughts and the process of possible intrusions of intruders.

Wrong way: do not develop a secure application by default.

FAQ


All of the above is easy to understand wrong - let's clarify something.

What is the purpose of your site and why are you swimming against the current?
The goal is to start a discussion about modern techniques and extreme points of view.

So you say that object-oriented programming is bad or good?
No, of course not! The point is that you understand: it is not necessary to solve all problems exclusively through the OO paradigm. You can not divide everything into black and white, this is a mistake. Within the framework of one application, there can be a variety of problems, and sometimes the best solution is to use different paradigms depending on the specific situation. And if you solve a problem with an inappropriate way, it will not lead to anything good.

Are you saying that frameworks are evil?
We do not specifically condemn frameworks. We only condemn their continued use on top of PHP.

If the framework helps me to quickly start and continue to work, what's wrong with that?
If you analyze the situation and the long-term consequences and realize that “quickly start and continue to work” is the only problem you have ever solved, then there is nothing wrong with that. But then we are not talking about programming or software development, but about using point-and-click solutions.

Getting started and working quickly is not creating an application; This means that you did not analyze the problem and did not realize the long-term consequences of your choice.

Are you saying that third party packages are bad?
Not. We recommend using third-party libraries. A code that you can easily and without restrictions implement in your projects. This is a great opportunity!

Who you are?
Our site is dedicated to the idea of ​​fighting extremism in the PHP community, and not to personal advancement or gaining fame. If we reveal the names - it will only distract attention from the problems raised on the site. Let's not be distracted.

What is your experience in software development?
To come to the ideas, thoughts and decisions reflected on our site, you do not need much experience if you always do what others say.

Recommended literature


  1. PHP: Wrong way - on Hacker News . When we launched our site, many comments appeared on Hacker News, reflecting quite a few valuable arguments.

  2. How to program without OOP . A fresh and alternative point of view: Brian Will in three videos talks about not starting with the PLO. In conclusion, he gives a few comments on how to write non-OOP code.

  3. Coders at work. Reflections on the craft of programming . Interviews are based on almost 80 hours of conversations with 15 of the greatest programmers and computer scientists. Here you will find a multifaceted story about how they learned to program, how they honed their skills and what they thought about the future of programming.

  4. Traits of a qualified programmer . Competence means enough experience and knowledge to complete a task. Qualification is knowing why you are doing something in this way and how it fits into the big picture. In other words, a qualified practitioner is always a competent practitioner, but the reverse is not necessarily true.

  5. Guides to safe programming . A technology-independent document with a set of common secure checklist programming techniques that can be embedded into the software development life cycle. Using these techniques, you will avoid most common vulnerabilities.

  6. Principles of safe design . Web application security is an integral component of any successful project, be it an open source application, a pass-through web service or proprietary business sites. , . — , , -. , , .

  7. : PHP . - : , . , .

  8. . . , , . . , , . 40 , , . . Java, -.

  9. . , .

  10. . , : , , . , , .

  11. . — , . , : «» . « » , :

    • ,
    • ,
    • ,
    • .

Source: https://habr.com/ru/post/308788/


All Articles