See, this is what modern PHP should look like

Time:2022-5-5

This is a community collaborative translation article. The translation has been completed. For more information, please clickIntroduction to collaborative translation 。

The title of the article is really pretentious, isn’t it? Yes, although we have worked with PHP for many years, can we tell which are the best practices and tools? I can’t, but I’m going to do it.

I see that the way developers work with PHP is really changing. Not only because the new version of PHP and its gradual improvement have made the PHP language change greatly and become more mature and robust, but also the whole ecosystem is constantly changing.

In order to make the code more elegant and easier to understand, people have created new tools, libraries, frameworks and articles, and defined new design patterns. Some people are still thinking about how to make work (and developers’ lives) more productive, concise and interesting.

I am not an early follower of a new trend. In fact, I will only use a new tool after it has a community and I think it can improve my work. What I often do is just try to write code using best practices.

Therefore, it took me some time to start using tools such as composer and phpunit. About a year ago, I opened my heart to these shiny new things.

First PSR, then composer, phpunit, Travis Ci and several other libraries and amazing tools. I’ve even started using IDE (VIM FTW, but phpstorm with Xdebug is a wise working environment)!

What is modernization?

Author:Karen Roe (Flickr) [CC BY 2.0 (http://creativecommons.org/li…)]

There are a lot of articles on the Internet about how terrible PHP is, how bad your life will be if you work in PHP coding, how ugly the language is and anything else you can think of!

If you plan to use legacy code, your life may not be very good, but if you have the opportunity to participate in a new project and be able to use all the new tools, you will see the new PHP I want to talk about.

I use PHP to deal with some problems every day, but people can’t pay attention to the changes in language, community and ecosystem. Although there is still a long way to go, things in the PHP field are becoming more and more mature.

I started creating an SDK of internal APIs for the company I worked for, such as a pet project, and decided to follow best practices. I’ve been doing most things, but I’ve made some changes when I’m doing something. These changes and what I learned last year are the subject of this article, which I call modern PHP.

Let’s start with the workflow

As I said, I haven’t used IDE for long, but I’ve loved it since I used it. Phpstorm is the top masterpiece in software. It will be my first and only ide since then. It’s my first attempt. It’s so good that I don’t have to try other ides.

The integrated Xdebug is perfect, as well as PHP namespace parsing, composer, GIT, automatic code completion, code generation and code reconstruction. Let me say three days and three nights.

I don’t think you have to use ide. In fact, it’s entirely personal. You need to use things that meet your needs, such as VIM, atom, Emacs, bracket, NetBeans, phpstorm, eclipse, and so on. Two important points are productivity and ergonomics. Your ide or text editor must help you work, not drag you down.

However, for me, a very important point is the integration of debugging functions. Write a large project (in fact, small projects are the same). You need a good debugging tool. Let’s forget thatvar_dumpandprint_r。 You need to set the value of variables, analyze the stack, and set breakpoints when the code runs. These are crucial, they make development and refactoring easier.

I don’t even know if there are other options. Xdebug has everything you need. Do you have time now? If you haven’t done these things yet, please take a moment to install Xdebug and integrate it into your ide. From now on, use the right tools to debug your code.

Another tool I want you to notice is GitHub. You can write a big article about how great GIT and GitHub are and why you have to start using version control to manage your code, but here I want to show you another reason.

The focus here is integration(GitHub Integration, translator’s note).

GitHub also integrates several other tools, and you should start using them. In the process of continuous integration, these tools can generate data for you, run tests, run tasks, and do all kinds of things for you in your workflow. Integration is a good reason for you to start using GitHub. Everything else can be sidelined for the time being.

Dependency management

Another point of modern PHP ecology is the dependence on management, from which composer came into being.

Composer is five years old, but large-scale application is still nearly two years old. This is probably because I didn’t use it early, or most PHP developers linger.

It is the terminal of packagist, which is the repository of PHP packages. It is composed of PHP libraries, projects and tools. The source code is saved in GitHub (or bitbucket, etc.).

All third-party libraries mentioned in this article can be easily added to your project.

$ composer require package_vendor/package_name

If you don’t know the name of the third-party library, you can usesearchFind.

$ composer search package_name

Composer is the perfect choice for managing dependencies, but not just that. Take the time to install composer and read itsfile

Properly handled command line interface

I’m really willing to try the idea of using the CLI interface quickly. For me, the greatest repl tool isIPython。 The tool automates your code, allowing you to easily define functions, leisurely access documents, and many other amazing features. To our disadvantage, the tool is used for Python rather than PHP.

In the PHP world, there is something called “interactive mode”, which can be accessed through terminal tools. Just type the following code:

$ php -a
Interactive mode enabled
php >

In this scenario, I am in interactive mode and can start testing some things. It works, but it’s not intuitive. I still tried hard several times. Because I know the ability of IPython, I won’t continue to use this mode at all.

Fortunately, there is a cool new cli tool called psysh. Psysh is an amazing tool full of compelling features that can be installed globally or by project using composer.

For me, the best psysh feature is the embedded document function. Directly query the document of a PHP function without running to PHP Net website, it’s great. The downside is that you have to do a few things before you can enjoy all the features.

After the tool is installed, in order to run correctly, you need to enter the following command (I use Debian here, which may not be suitable for everyone):

$ apt-get install php7.1-sqlite3
$ mkdir /usr/local/share/psysh
$ wget <http://psysh.org/manual/en/php_manual.sqlite> -o /usr/local/share/psysh/php_manual.sqlite

The first command is not mandatory, and if you have SQLite installed, you can skip this step. The second command creates a directory to store documents, while the third command downloads and saves documents to the previously created directory. Remember, all these commands must berootRun as.

Now you have these:

psyshScreenshot of instruction document description, showing aboutjson_decodeInformation about.

Click this link to go toPsyshLearn more about this cool tool.

You should start the test

This is the spell I say to myself every day. Like many people, I didn’t test the code as recommended by TDD. I have formed the habit of testing now, and it has lasted for half a year, but there is still a long way to go.

When I was faced with a complex legacy project, I decided to study testing. The code of that project is so wonderful that any time I add some code, there will be problems. With new features? Realize function and manufacturing problems! Fix a bug? Let’s create a new one.

That’s a big problem. I’m hereAnother article, and I started trying to use tests.

The first tool I would like to recommend isPHPUnit。 As the official website shows:

Phpunit is a PHP testing framework for programmers
Phpunit is a unit testing framework of xUnit architecture

Therefore, phpunit is a framework for generating unified tests for your project. It will provide some functions to test your code and have beautiful results.

Since I started thinking about testing, reading and talking to people, I’ve found another great tool that will complement your work in these unified tests. It is behat, a BDD framework for PHP.

BDD (behavior driven development) is a development process from TDD (Test Driven Development). These acronyms are not important now. What’s important is that you can specify your test in a more natural language that non-technical people can understand.

This language is called gherkin and is used to describe the expected behavior under test. Gherkin’s test description is used as follows:

These lines are followed by PHP code, which will be called only if there is a match between the line specified in the phpdoc of the method and the regular expression. The code uses your SDK, application or web system to implement these steps and the actions that real users will perform

Behat’s workflow is very smooth. After everything is configured correctly, you can start writing all possible solutions for testing functions. When you first run behat, it will provide you with all the method templates you should add to the PHP context class to implement each step in the scenario.

After that, you can write the actual code for each step and repeat the cycle.

  • Write PHP code for each step
  • Run test
  • If everything is OK, write PHP code for the other steps
  • If something goes wrong, fix it

After configuring and reading the documentation for half an hour, you can prepare to use behat. In the end, you will find that it is all PHP code and you have found that you already know how to program with it.

Continuous integration

Continuous integration (CI) is a process that provides a way to create software for software engineers.

Simply put, it is the act of integrating small pieces of code into the underlying code often (perhaps several times a day). The code has been tested and there will be no emergencies. Ci helps us build, test and deploy our applications automatically.

With just a few clicks, you can integrate your GitHub project into Travis CI. After each time you push the code to the warehouse, it will run the phpunit and behat files you created and tell you whether the recent functions have been prepared, or not, or will be merged. In addition, you can use Travis Ci to deploy your code to run in a production environment.

It is very good to complete the workflow through a clearly defined workflow. Travis CI can help us complete this work. Read this articleGetting started, understanding the software development process is so interesting, not just the code itself.

Follow psr-1 and} psr-2

If you’ve heard of PSR, you should know it right away. In fact, PSR is the abbreviation of PHP standard recommendations, which is made byPHP-FIG(PHP framework interop group). Php-fig is an organization composed of members of some large PHP projects, frameworks and CMS. It aims to think about the future and ecology of the language and discuss the standards that should be followed in the language.

For a long time, PHP has no coding style. I’m not very old, but every time I look at other people’s projects or libraries, they use different coding styles. Sometimes the curly bracket is in this position, and sometimes it is in the next line. There are several ways to deal with a long line. A variety of different coding styles and preferences are mixed together in a mess.

Php-fig has done a lot of work. By introducing a unified coding specification, they seem to be saying: “stop worrying about coding style, let us all follow a standard, and then focus on the production of good software”. Now, whenever you want to read someone’s code, you just need to care about how the code works without blaming his code style and structure.

Up to the publication of this article, 9 PSR standards that have reached consensus have been launched, providing general solutions for general problems. If you don’t know these standards, start fromPSR-1AndPSR-2Let’s go.

These standards propose the coding style of modern PHP, so make sure you’ve read them and started using them. Don’t think you can think about them all when writing code. It’s a long process, but you should know that there are some tools to help you use and remember them.

PHP CodeSnifferIs a tool that you can find and install using composer on packgist. I don’t think the name of this library is ideal because it actually contains two tools, phpcs and phpcbf.

Phpcs is used for code style detection. It will comprehensively scan your code to find out those parts that do not meet the configured coding specifications.

You can use many coding specifications built into phpcs, or you can customize the coding specifications. At the end of the scan, it will list the code fragments that do not meet the coding specifications for you, which is great.

So, how can we correct the mistakes? You can open every file, change the code, run phpcs to see if there are any errors, and then repeat the process. Very boring.

To solve this problem, PHP codesniffer provides another tool called phpcbf or PHP code beautifier. Run phpcbf under the same set of coding specifications, and it will try its best to correct all errors for you without damaging your code.

Try to establish the habit of running phpcs and phpcbf before code submission, which will ensure that all your code meets the coding specifications. If someone likes your tool (or project) and wants to contribute code, they will have no obstacles in reading your code.

frame

I’m not going to spend too much time discussing frameworks. Now there are some good frameworks, either popular or niche. Personally, I prefer not to use those heavy-duty frameworks with all the functions built in. My idea is that you just choose the one you need.

If you need an HTTP client, you can use guzzle. If you need to use a template engine, you can use twig. If you need a route, find a component that meets your needs and use it. Assemble these components and build your own application.

SymfonyThe framework has done great work in this direction. You can use the entire framework for your project, or just select and use a portion of what you want to use. It’s that simple.

However, whenever I want to use a framework to complete an application, I always choose one of those frameworks called micro frameworks. They are really light, only provide basic functions, easy to customize, and can easily adapt it to your project architecture.

The micro framework I chose isSlimframework, I think you should read it. It’s really simple for working with small projects, but it’s a little complicated for larger projects.

By the way, I think you should always choose a framework that belongs to you and use it by yourself. This will allow you to understand the operating mechanism of the framework and adapt to large frameworks faster.

Modern PHP Toolkit

Let’s end the article with a series of toolkits. For me, these components, tools, and libraries depict what modern PHP looks like:

  • Slimframework: a nice, cool small framework
  • Symfony: a heavyweight framework composed of many excellent and reusable components
  • Guzzle:: clients that can easily initiate HTTP requests
  • PHPUnit: a test framework
  • Behat: behavior driven testing framework
  • PHPCS/CBF: code specification and beautification tools
  • Faker: library for generating test data
  • Psysh: full of amazing interactive consoles
  • Composer: it depends on management and has many other useful features
  • Packagist: PHP package warehouse
  • Twig: template engine

I know the title of the article is really arrogant. In fact, what I want to say is that PHP is evolving, and the PHP ecosystem is progressing at the same (perhaps faster) speed.

For discussion, please go to:https://laravel-china.org/top…