Why Go is a powerful language to learn as a PHP developer

Since 10 years, I have been programming with PHP professionally. After getting a computer engineering degree, all I know is that Java is no longer my side dish (using Java for more than 6 years in personal and academic projects), I wanta lot ofWith a simpler stack, I found that a quick way to market yourself as an independent developer is to enter the growing PHP CMS market.

Over the years, PHP has changeda lot ofAlthough many people like to attack or criticize it, many people do so based on very old and very little experience. Modern PHP (especially if you are willing to use PHP 7 types and discard PHP 5.x) is very easy to use. Of course, for some reason, PHP has the advantage that the language can be deployed almost everywhere, which is why many CMSs use PHP's built-in, and why it is so successfulbecauseThey are based on PHP (gravityinclude).

Of course, PHP is just a tool, and I have been studying Go in depth recently.

Compared with PHP, Go is a completely different language and environment.

This is not an article designed to get you out of the hustle and bustle of PHP, but to introduce you to PHP developers and why Go is a good language that can be used as a tool to learn.

First of all, what is Go?

Go is an imperative, object-oriented programming language designed by Google 10 years ago.

The comprehensive knowledge of the founding members and the original philosophy of creating the best language to meet their needs led to Go.

Go is a statically typed compiled language with built-in garbage collection and concurrent programming functions.

Nothing new

The way Go innovates is very interesting. It completely ignores the hype about the new features that modern languages should have and the features that other programming languages provide. Instead, it replaces the core concepts that are picky from the tried and tested languages, and aggregates decades of programming experience into a beautiful Tools to use.

The task of the programming language designer is consolidation not innovation – Hoare, 1973

Go has many unique features, of course, it is more than just a mashup language. Go to introduceRoutine, This is an excellent way to deal with concurrency. Go to introduceput off, Which is a good way to perform operations when the external function returns (now also added to Swift).

Go is the first language to introduce formatters in standard tools. And the ability to compile for other platforms without friction, and more "new" things.

Go takes root. Robert Griesemer's wonderful speech at GopherCon 2015 illustrates this point: Go combines many principles of the twoCAnd Oberon-2, which is a language from the Pascal family. Both languages originated from Algol 60, which was introduced in 1960.

So next timeSomeone asked why Go looks like a language from 20 years ago, You can also answer that it actually has more than 60 years of experience. As Robert Griesemer once said, it will take 10 years for a programming language to become mainstream.

Go is just getting started, and I'm very excited about its future and what people can build with it!

Go is a complement to PHP

If you use Ruby or Python in addition to PHP, you may have realized that if you remove fanaticism and personal preference from the equation because they are all interpreted, loosely typed languages, then they are more or less It can be boiled down to different versions of PHP.

You can convert Ruby to PHP and Python and then do the same thing. The only "Internet language" that is very different isJavaScript, Which is different due to the non-blocking model (but has been migrated to other languages through the library, including PHP and non-blocking model) and because it is currently the only language that runs natively in the browser, which brings it A huge advantage. Moreover, it is an uncontrolled execution environment, a wilder ecosystem, all of which can differ in subtle ways.

On the other hand, this is a completely different beast. It is a system language, such as C. Unlike dynamic languages, Go runs very fast.

PHP is built in C, you can write and run PHPCExtension, so the concept of system language should notthatStrange to you.

Go can replace your web stack, and you can use it to simplify the web framework, but PHP still has a place, especially when prototyping, you still don’t know which part of the code needs a lot of optimization, and after all, whether your code is real Will be used.

So, when should you use Go? When you use PHP, PHP is not really the best tool. If PHP takes up too much memory or resources for a particular function, the performance of a highly optimized Go program will be better. It's that simple. PHP 7 is amazing in improving PHP performance. That is a free gift. However, if you need to process millions of database entries, or need to run for a long time to get gigabytes of data from an API, PHP may not be the right tool.

I rely onNode.jsThis problem has been solved for many years, but as far as I know, everything I have proposed in Go so far is a simpler and better solution.

Of course, it doesn't stop there. With Go, you can easily build cross-platform concurrent applications. This is very different from PHP web development. The method is more challenging, but personally, it is also more interesting. It can bring you many Meaningful work.

Therefore, as a PHP developer, you can start putting difficult tasks in the hands of Go, and mastering it well will definitely enrich your career choices.

Why choose Go instead of CC ++ or Java?

Any language has its place. Of course, Go cannot beat C and C++ performance. You can find many benchmarks.

Go is between these two mainstream languages and historical languages and dynamic languages: you want more performance than interpreted languages can provide, but you are not ready or unwilling to use C or C++, they Although they are faster, they are too low-level, you need to manually manage the memory, which will take more time to develop. Go for that place.

For highly optimized code, if you are proficient in C or C++, they may be a better solution. I can say the same to the conference.

Compared with Java, the situation is completely different. Java requires a lot of overhead in terms of environment, while Go programs are single files, lightweight, portable and native.

And we may be comparing apples to oranges. You will never use Go where you use Java, but the opposite is true.

The heart is simple

(And remember: simplicity does not mean easy) Avoiding functional creep is obviously one of the goals of Go designers. The legendary Ken Thompson is one of the three original designers of Go and the creator of UNIX and B (and many other things), he once said

When the three of us (Thompson, Rob Pike, and Robert Grisemel) started, it was pure research. The three of us were together and decided to hate C++. [Laughter]...[Back to Go,] The idea we started was that all three of us have to talk to every feature of the language, so no extra rubbish will be added to the language for any reason.

For any experienced developer coding in any language, this leads to an extremely simple language.

Java, C++, C, C#, Erlang, JavaScript, Swift, almost all modern programming languages are more complex than Go.

Here, I mean using complex language for programmers, complex language for reading, complex language for becoming a proficient person. Internally, Go hides all the complexity and exposes a simple API. Go not only has a garbage collection function, but also has no public memory management functions at all.

Imagine that PHP has 67 keywords, and Go has 25 keywords.

The key here is that our programmers are Google employees, not researchers. They are usually quite young and have just graduated from school. They may have studied Java, or C or C++, or Python. They cannot understand great languages, but we want to use them to build great software. Therefore, the language we provide to them must be easy to understand and adopt. --Rob Parker

This is the core of the Go language philosophy and explains why Go chooses to avoid implementing features (avoiding feature climbing), and why many concepts of functional programming are excluded because of their complexity. Pure functional programming is too far away from the machine concept to be related to Go, which is a core command language.

In other words, Go implements many functional programming concepts, such as first-class functions (allowing functions to be assigned to variables), closures, and recursion.

But compared to PHP or JS, you don't have functional operations such as map, reduce, or filter, and you have to rely on loops. why? Because these operations are inefficient, Go must find a balance.

When it comes to missing things, there are no exceptions to handle errors. No class (even if it is object-oriented, has a structure with associated methods, mandatoryComposition beyond inheritance—If you know the knowledge of JavaScript's prototype object implementation, it will be familiar, but there is a big difference), no need for generics (although PHP does not have generics), andThis is why.

less is more, Or (even better!)Less is doubled.

The "secret" of good software design is not knowing what to add to the code. That is knowing what is left! This is identifying where the hard and soft spots are, and knowing where to leave space/rooms, rather than trying to cram things into more designs.

There is only one way to write a loop:for. forgetwhilewithdo — whilewithforeach(Are there any more?).

[...] What makes Go successful is that the language misses as much content as it contains.

The ability to return multiple values from a function avoids a lot of trouble (the simplest example is to return an array containing 2 values, and you must extract them without knowing the exact type passed).

Tools inherit simplicity.gofix automatically fixes breaking API changes in the new Go version.

Go is simple in design and will always remain simple.

As Rob Pike saidMany other languages are copying functionality with each other, losing their unique aspects (for example, JavaScript introduced class syntax to please Java and PHP developers), and they are ideally integrated into conceptually unique languages.

Go cannot compete on functionality. This reminds meThis more and more authentic article.

Beware: Go is polarized

Go has many fans and many haters. As a PHP developer, I'm sure you have developed a thick skin in this flame war, and we can quickly move on to the next step. It is very popular, and developers have strong opinions.

No matter what trade-offs you make, there will always be criticism, because no programming language can be perfect.

Go solves the problem well. And you don’t have to be a genius to start using it, although it may hurt your feelings.

Go is very self-righteous and has a clear agreement

The first thing you will find about Go is that almost all the code you can find is almost the same.

This is because Go has clear and mandatory conventions. The built-in tool provides 2 commands related to the agreement (gofmtwithlin, Which contains the first automatic formatting code, the second only displays warnings), they can check whether your code meets the requirements, and even automatically adjust the style according to Go guidelines.

This is different from JSESLint/ JSHint, because these tools are team-wide applications. Just like in all JS, you can customize anything in the preferences.gofmtThere is no configuration, this is the style to follow.

This is very useful for providing consistency on your own code (the code you wrote 5 years ago in PHP or JavaScript might bevery muchDifferent from your current conventions and preferences) and codeeveryonedistribution.

Imagine that there are no more internal teams discussing the best code style. Imagine that all PRs in an open source project are formatted and deleted in the same way. Separate the vs0 tab to save thinking cycle-it is a tab. Are the braces on the same line or on the next line? Always the same line (there is a reason, it allows the semicolon to be omitted).

If variables or imports are not used, Go will cause compilation errors to prevent the program from accumulating garbage over time.

The naming convention is so important that the access modifier has been completely removed from the equation. Lowercase variables? private. Uppercase variables? Listed. So simple, a simple agreement eliminates a lot of useless screen space usage, and it is immediately understandable.

Comments have special needs, you can use special syntax to write comments so that you can use the following command to check the packagego docAnd you have all the documents you need without having to search on Google.

go getThe built-in (available for open source and distribution) is for you to use. Although in my opinion, PHPland is much more advanced in dependency management.

PHPUnit/code receiving? No need,go testAlready at your service*_test.gofile.

It makes you a better programmer

If you are from PHP, then learning Go will make you think in a whole new way. This will make you a better programmer, just like learning any other language: it introduces you to new concepts. If you feel unfamiliar and unfamiliar, it means that you are learning and growing as a developer is a good sign.

First of all, Go is compiled rather than interpreted. Completely different workflow and deployment.

If you have no experience with strong typing, it will be a paradigm change. PHP 7 comes with a type checking function, if you don't have to support the old version of PHP, it will provide a great help. Go is strongly typed. Many, if not all, type problems are resolved at compile time.

Go is very simple and designed to be very simple, and becoming a Go developer means to recognize this simplicity and use it instead of trying to write Go similar to Java, but to accept it.

Simply put, I am not saying that Go is a toy language, of course it is not, and I am not trying to introduce someone to a coding language.

In short, I mean moreMinimalismwithNo fluff.

When a language provides you with multiple ways to do the same thing, you have to think about which is the best, which will distract you from the problem you are trying to solve.

You can run Go code from PHP

Therefore, one way I suggest at the beginning is to write some heavy routines or long-running code, which will take up too much memory as a Go service.

ThereYes a lot of methodCall Go programs directly from PHP, but you can also choose to implement oneService queue via ZeroMQ, Or expose the API endpoint through the reverse proxy to access the long-running go program. You have many choices.

Go's special weapon: concurrency

As we all know, PHP-FPM can handle concurrent requests well, spawning a new process that executes the actual PHP code for each user. Usually, in web applications, the database is the bottleneck. But what about long-running processes (something you really don't want to build in PHP), or need to start a heavy calculation loop in a PHP request (you need to run thousands of concurrent processes in it)?

PHP has thread support, so it can perform concurrent processing, but PHP (even C and other languages) can use libraries outside the language for concurrency, and Go isDesignedIt has built-in concurrent programming and provides a native way to communicate between goroutines.

Heavier threadsRoutine. A system can support 10k threads, and the same system can support millions of goroutines, because the internal implementation of goroutines consumes much lighter memory, such as Java or Erlang.

Therefore, even if you don't need millions of concurrent requests, the performance improvement is obvious.

In addition, it is very easy to digest goroutines and understand the role of the code in a simple way.

No need to extend classes or include special extensions, these extensions may not always be available (this effectively limits the extent to which we can use PHP concurrently for distributed code that is installed on our own)

Just entergo someFunction()Then the function will be executed in the goroutine.

in conclusion

If you are a novice PHP developer in Go, I hope you are now curious about this tool and consider where it is useful or whether it is suitable for you.

If you are a programmer who prefers simplicity over complexity, but prefers direct and readable code instead of abstraction, then I believe you will find Go really interesting.


More tutorials: