Php Deployment Tools

PHP Deployment Tools: A Guide to the Best

PHP deployment tools can make your life as a developer easier. They help you automate processes and streamline your workflow, so you can spend more time doing what you love: writing code.

In this article, we’ll walk through everything you need to know about PHP deployment tools—including the top 10 best ones on the market right now—so that you can find the right one for your needs.

Php Deployment Tools

TOP 40 Static Code Analysis Tools (Best Source Code Analysis Tools)

GitHub
If you are a developer, then you must know about Git for source code management. Developers use GitHub when it comes to interaction with multiple team members and open source contributors for developing coding solutions. I’ve written a short series on Git for beginners covering, commands cheat sheets, Branches, Conflicts etc.

The best thing about Git is that it allows developers to create custom workflows manually, or by integrating third party PHP deployment tools.

Cloudways allows you to deploy code of your application from your Git repositories. Your Git repository must support Git over SSH for this to work. For Git deployment, you must follow simple steps given below.

Signup & Launch Server
First of all, signup at Cloudways and launch your server and application. Next, move to the Application tab by selecting any app from application page .

cloudways-server
Generating SSH Keys
Here, you must download SSH keys by moving to Deployment via Git tab,

We will use these keys to allow access from your Cloudways server to your git repository. Now click on the Generate SSH Keys button to generate the keys.

generate-ssh-key
Now, click on Download SSH Keys to download SSH Public Key that we will use in the next step.

view-ssh-key
ssh-key
Upload SSH Key To GitHub Repository
On Github, navigate to the repository and find the code which you want to deploy. If you are using another Git service, you will have to find the equivalent way of deploying them. Go to Settings -> Deploy keys and click on the Add Deploy Key button to add the SSH key. You can also give a name to this key in the title field and copy the key to the box. Click on the Add Key button to save the SSH key.

Copy the SSH Address Of Repository
Copy the repository address as shown in the image below. Make sure to copy the SSH address as other formats (like HTTPS) are not supported.

Deploy Code from Your Repository
Go back to Cloudways console. Paste the SSH address you got in Step 4 into the Git Remote Address ” field.
Select the branch of your repository you want to deploy from. In this example, we are using the master ” branch.
Type the deployment path (i.e. the folder in your server where the code will be deployed). Make sure to end it with a backslash (/) . If you will leave this field empty, the code will be deployed to public_html/ .
Click on the Start Deployment button to deploy your code to the selected path.
deployment-via-git
Repository Successfully Cloned
You will get a notification once the deployment process finishes.

You have further options to delete the repository from the server (no files will be deleted, see FAQ below). Pull the latest changes or change the branch you deploy from.

successfully-deploy-cloudways
DeployHQ
DeployHQ is an amazing PHP deployment tool to automate your deployments from Git, Mercurial, and Subversion code repositories. Git-based deployment is now becoming de-facto standard in any good development agency. This makes lives easy as it reduces the hassle of uploading and downloading source files.

In this post, I will describe how you can integrate DeployHQ with your web app that you have hosted on Cloudways. This integration will ensure on-the-go deployment of the code. With Cloudways staging-friendly environment, developers can experiment with their code as much as they want.

So, here are the steps.

Create a DeployHQ account
Register an account on DeployHQ. (You can use this free account for one project and 10 deployments per day)

Create a new project in DeployHQ
You will need to create a project to start your deployment process.

Connect DeployHQ with your code repository
Enter the details of your code repository (or “code repo”). DeployHQ has out-of-the-box support for popular code hosting sites, like Github, Bitbucket, etc.

Add Path Of Github Repository
To begin with deployment, you need to add the repository path from GitHub like this.

Configure the server
Select SSH/SFTP as protocol

Then, fill up the SSH Configuration.

For example, you may need to change the branch from master to any other branch that you like to deploy from.

Now, click “Save”. You have successfully configured your server

Deploy
Click “Deploy Now”. On the deployment screen, you can click the “Deploy” button to start the deployment process instantly.

DeployBot
For software development teams, automated deployments have become imperative to the process flow. Manual deployments are error-prone. They sap energy and effort of the team members.

Any managed cloud hosting platform which claims to be a high-quality solution must provide the ability to automate deployment. This is why Cloudways does exactly that. Earlier, I had explained how to automate deployment using DeployHQ.

You can also achieve deployment automation using DeployBOT (or dploy.io).

Deployment using DeployBOT
DeployBot is a PHP deployment tool that connects your code repositories to your servers. In this article, I will describe how you can deploy your code on a Cloudways server using DeployBot.

Create a DeployBot Account
You can create an account for free which you can use for a single repository.

Connect a repository
DeployBot has out-of-the-box support for GitHub and BitBucket, but you may also connect to other repositories.

Configure the environment
By default, the deployment will be manual. However, you can change it to ‘automatic’ to start the deployment whenever a change occurs in your repo. You may also need to change ‘master’ to the desired branch which you want to use.

Configure the server
Select SFTP under Files section.

You can get the login credentials from the Master Credentials section within the Cloudways Server Console.

php complexity analysis

Installing the Code Quality Tools

There are always multiple ways to install the tools described here.

My personal preference is to use composer’s global package installation using cgr to avoid dependency problems on the global scope.

You can as well use the PHAR format, in most cases.

You can refer to the documentation of each tools to have every possible ways of installing them.

How to Use the Tools

In Your Terminal

All the tools can be used in the terminal. Most of the time you just need to pass the codebase’s path as an argument and voila! I describe this process for every tools in this article.

I advise you to call the tools from the main folder of your project. Every examples assume that your codebase is in the folder src.

In Vim / Neovim

You can easily configure in Vim every tools you want and let them parse your open files.

With the plugin neomake you can plug easily PHPMD, PHPSTAN and PHPCS to Vim. It will display in the gutter warnings and errors. Very handy!

You can even create your own makers to use every php code quality tools you want. As a reference you can consult my neomake config file.

In PHPStorm

Since I don’t use PhpStorm anymore, I won’t explain how to install these tools in the IDE.

Nevertheless here some handly links to Jetbrain’s documentation:

  • PHPMD
  • PHPCS

PHP Quality Tools: The Essential

I wouldn’t write any line of code without the following plugins. They will format your code properly and gives you precious advice.

PHP-CS-Fixer (PHP Coding Standards Fixer)

  • Github

Let’s begin by the cause of long meetings, hatred behavior and murder impulses: code formatting rules. A great example of Parkinson’s Law of Triviality.

Personally I don’t have any preferences regarding code formatting. What I care about is to have a consistent one:

  • It’s easier to read
  • It frees your mind for more important questions

PHP-CS-fixer is a simple tools which allows you to format your code automatically. By default PSR-1 and PSR-2 rules are used but you can define your own formatting rules.

With the following command you can format an entire codebase:

$ php-cs-fixer fix src/

You have as well the possibility to preview the modifications without applying them (--diff option) or you can precise the rules (--rules option) you want to use.

PHPCS (PHP CodeSniffer)

  • Github
  • Documentation

PHP CodeSniffer is a very good tool to output the coding standards violations you have in your codebase. Two command line scripts can be used: phpcs to output the actual coding standards flaws, and phpcbf which can fix some errors for you.

You can type for example:

$ phpcs src/

The output will look like that:

FILE: /home/superCoolUser/mySuperProject/src/Model/SuperModel.php
------------------------------------------------------------------------------------------
FOUND 6 ERRORS AND 1 WARNINGS AFFECTING 7 LINES
------------------------------------------------------------------------------------------
  2 | ERROR   | [ ] Missing file doc comment
 14 | ERROR   | [ ] Missing @category tag in class comment
 20 | ERROR   | [ ] Missing doc comment for function __construct()
 34 | WARNING | [ ] Line exceeds 85 characters; contains 93 characters
 57 | ERROR   | [x] Opening parenthesis of a multi-line function call must be the last content on the line
 60 | ERROR   | [ ] Expected "if (...) {\n"; found "if(...) {\n"
 63 | ERROR   | [x] Closing parenthesis of a multi-line function call must be on a line by itself
----------------------------------------------------------------------------
PHPCBF CAN FIX THE 2 MARKED SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------------

As you can see phpcbf can fix automatically two errors for you by typing:

$ phpcbf src/Model/SuperModel.php

You can use the default coding standard shipped with PHP Code Sniffer or you can easily implement your own.

PHPMD (PHP Mess Detector)

  • Official website
  • Documentation

PHPMD will display the possible bugs and misuses of the language in your application.

Here how to do the magic:

$ phpmd src/ text cleancode

PHPMD will scan the directory and sub-directories of your project and output in plain text the errors found. You can as well create an html or xml output by replacing the text option in the command line above.

In this example we use the cleancode ruleset but you can obviously change it or create your own.

You want to output the errors in a file? Easy:

$ phpmd src/ html cleancode --reportfile ~/phpmd.html

If you choose xml as output you will have more information regarding the rule set as following:

  <file name="/home/mySuperUser/mySuperProject/src/randomClass.php">
    <violation beginline="61" endline="61" rule="BooleanArgumentFlag" ruleset="Clean Code Rules" externalInfoUrl="http://phpmd.org/rules/cleancode.html#booleanargumentflag" priority="1">
      The method notThatCoolMethod has a boolean flag argument $badBoolean, which is a certain sign of a Single Responsibility Principle violation.
    </violation>
    <violation beginline="102" endline="104" rule="ElseExpression" ruleset="Clean Code Rules" externalInfoUrl="http://phpmd.org/rules/cleancode.html#elseexpression" priority="1">
      The method superMethod uses an else expression. Else is never necessary and you can simplify the code to work without else.
    </violation>
  </file>

You can see for example the priority of the rules violated. You can then refine your result by using the --minimumpriority option for example.

In short: PHPMD is a great tool I really encourage you to use. It will detect a lot of potential problems in your code and will save you hours of debugging.

Your boss will be so happy he will increase your salary by 200%. Guaranteed.

PHPStan (PHP Static Analysis Tool)

  • Github

PHPStan is another tool to have in your toolbox. It aims? Output errors like a compiled language would display during compilation. It’s a good complement to PHPMD.

You can run it as follow:

$ phpstan analyse src/ --level=7

You can precise the strictness of PHPStan with the level option. The minimum is level 0, the maximum level 7.

To give you an idea here an example of output:

 ------ -----------------------------------------------------------------------
  Line   src/MySuperModels/RandomModel
 ------ -----------------------------------------------------------------------
  78     Instantiated class App\Service\Api\InvalidArgumentException not found.
  82     Instantiated class App\Service\Api\InvalidArgumentException not found.
  93     Method App\Service\Api\Client\ClientInterface::post() invoked with 3 parameters, 4 required.
  103    Casting to string something that's already string.
 ------ -----------------------------------------------------------------------

Like the other tools, you can create your own rules.

PHPUnit and the CRAP metric

  • Github
  • Documentation

This article is not about unit test. I assume you know that unit testing your code is far more important than anything present on this article.

PHPUnit can as well display a very interesting information: the CRAP metric.

CRAP uses the cyclomatic complexity with the code coverage of your code to display what might be the code difficult to change in your application.

More the CRAP index is high, more you code will be considered as “crappy”.

Indeed if your code has a great complexity but a low code coverage, you can expect it to cause unfortunate bugs each time you change it. You won’t even notice till your boss yells at you. Expect Dave, your colleague developer, trying to push you even more down for him to shine in the shadow of your shame.

To display the CRAP metrics, you need to produce a code coverage report:

$ phpunit phpunit --coverage-html ./tempFolder

This will create HTML files in the tempFolder directory. You can open the index.html in there and click on the dashboard link to finally contemplate the CRAP indicator.

crap metricJourney to the center of the CRAP

Please remember however: code coverage doesn’t mean that your code is well tested. This is an entirely different topic I will keep for another article.

Checking Your PHP Code Deeper

I use the following tools to make sure that the project I work on goes to the right direction. They can help you seeing the big picture.

They can as well be a real life savior when you need to work on an unknown (legacy) application. They can be a great help for refactoring.

PhpLoc

  • Github

PhpLoc is a very good tool to get an idea of the size of a project.

You can execute on your codebase:

$ phploc src

This will output something like that:

Size
  Lines of Code (LOC)                               61
  Comment Lines of Code (CLOC)                       0 (0.00%)
  Non-Comment Lines of Code (NCLOC)                 61 (100.00%)
  Logical Lines of Code (LLOC)                      23 (37.70%)
    Classes                                         17 (73.91%)
      Average Class Length                          17
        Minimum Class Length                        17
        Maximum Class Length                        17
      Average Method Length                          3
        Minimum Method Length                        1
        Maximum Method Length                        7
    Functions                                        0 (0.00%)
      Average Function Length                        0
    Not in classes or functions                      6 (26.09%)

Cyclomatic Complexity
  Average Complexity per LLOC                     0.26
  Average Complexity per Class                    7.00
    Minimum Class Complexity                      7.00
    Maximum Class Complexity                      7.00
  Average Complexity per Method                   2.20
    Minimum Method Complexity                     1.00
    Maximum Method Complexity                     4.00

Dependencies
  Global Accesses                                    0
    Global Constants                                 0 (0.00%)
    Global Variables                                 0 (0.00%)
    Super-Global Variables                           0 (0.00%)
  Attribute Accesses                                 7
    Non-Static                                       7 (100.00%)
    Static                                           0 (0.00%)
  Method Calls                                      14
    Non-Static                                      14 (100.00%)
    Static                                           0 (0.00%)

Structure
  Namespaces                                         1
  Interfaces                                         0
  Traits                                             0
  Classes                                            1
    Abstract Classes                                 0 (0.00%)
    Concrete Classes                                 1 (100.00%)
  Methods                                            5
    Scope
      Non-Static Methods                             5 (100.00%)
      Static Methods                                 0 (0.00%)
    Visibility
      Public Methods                                 3 (60.00%)
      Non-Public Methods                             2 (40.00%)
  Functions                                          0
    Named Functions                                  0 (0.00%)
    Anonymous Functions                              0 (0.00%)
  Constants                                          1
    Global Constants                                 0 (0.00%)
    Class Constants                                  1 (100.00%)

Those data can give you already some clues about the project:

  • Comment lines of code is never good. Get rid of it without a second thought.
  • Too high Average Class length is usually not good either. Split the god classes.
  • Too high Average Method length is again not good. For the sack of your colleagues, split them.
  • Cyclomatic complexity can indicate a bit everything and anything. Trusting something like CRAP might be wiser.
  • Avoid unnecessary Dependencies. Don’t forget that globals accesses, constants and variables can bring you many problems.
  • Avoid abstract classes as much as possible: remember, composition over inheritance.

In a nutshell: a very simple and valuable tool.

PHP Insight

  • Official Website
  • Github

PHP Insight is a pretty good static analyzer which will give you many advice to improve the quality of your code.

You can use it as follow:

phpinsights analyse ./src

First, It will give you a quick overview of your codebase:

PHP Insight first screen

Then, it will provide you many advice:

PHP Insight second screen

This is a really useful tool. You can as well format the output (JSON for example) or even create your own rules!

PHPCPD (PHP Copy past detector)

  • Github

PHPCPD will scan your codebase and output the code duplicated.

You can use it by typing:

$ phpcpd src/

PHPCPD will produce this kind of output:

phpcpd 4.0.0 by Sebastian Bergmann.

Found 1 clones with 44 duplicated lines in 2 files:

  - /home/superUser/src/superFile.php:11-55
    /home/superUser/src/superFolder/superFile.php:11-55

5.04% duplicated lines out of 873 total lines of code.

Time: 29 ms, Memory: 4.00MB

You can include multiple files instead of a whole directory, exclude some files (or paths) or even output the result in a XML file.

Keep in mind though: if you go to the DRY principle violation hunting in your codebase, keep in mind that code duplication doesn’t necessarily imply DRY violation.

PHPMND (PHP Magic Number Detector)

  • Github

This tools is pretty specific: it can help you to find magic numbers your code.

The easiest way to use it:

$ phpmnd src/

Here the output:

--------------------------------------------------------------------------------

httpClient/myHttpClient.php:98. Magic number: 200
  > 98|         if ($response->getStatusCode() != 200) {

--------------------------------------------------------------------------------

service/superClass.php:47. Magic number: 8
  > 47|         for ($i = 0; $i < 8; $i++) {

--------------------------------------------------------------------------------

You can play with a lot of options, like the possibility to ignore numbers, exclude files / paths / extensions…

dePHPend

  • Github
  • Documentation

Did you ever work on a project full of unnecessary dependencies, wondering how to understand this nightmare? Do you want to verify if your wonderful project is not mutating into a complex Big Ball of Mud?

dePHPend can help you grandly on that matter.

You can use it as follow:

$ dephpend metrics src/

This output will then appear magically:

example dephpend output

As you can see, dePHPend will output the number of Afferent Coupling, the number of Efferent Coupling and display an instability indicator based on them.

In clear:

  • No class depend on the class App\Kernel
  • The class App\Kernel depends on five other classes

The instability score is high here: this class couple other classes together but is never used!

You can as well output plain text or UML for example.

churn-php

  • Github

churn-php will display the classes you should refactor based on the cyclomatic complexity and the number of commit the class has.

This is a pretty interesting approach. A very complex class which is often modified has indeed a high chance to introduce bugs.

As the other tools it is very straightforward to use:

$ churn run src/

Here the result

+-------------------------------------------+---------------+------------+-------+
| File                                      | Times Changed | Complexity | Score |
+-------------------------------------------+---------------+------------+-------+
| src/Service/classToRefactor.php           | 12            | 8          | 0.441 |
| src/Service/anotherClass.php              | 3             | 15         | 0.185 |
+-------------------------------------------+---------------+------------+-------+

The higher the score, the greater the need to refactor.

PhpCodeFixer

  • Github
  • Documentation

Deprecated functions are bad. They can create very weird bugs difficult to debug. This tool can help you detect them in your shiny application. You can precise the version of PHP you work with and your main codebase directory as follow:

$ phpcf --target 7.1 src

And here the usual possible output:

phpcf output

PhpMetrics

  • Github
  • Documentation

Last but not least: if you are a metric lover, PhpMetrics will be your daily fix. It will output a lot of metrics about your project.

You need to type something like that:

$ phpmetrics --report-html=myreport.html src/

The HTML output will be full of diagrams and numbers.

Now keep in mind that metrics are not necessarily the absolute truth, it really depends on your project. I won’t explain everything this tool can output here, maybe in a future article?

Do we really need these tools to check our PHP code?

My experience showed me that software entropy is a real thing. More you will modify your application, more the application has chances to break. Your application will inevitably become more complex.

These PHP code quality tools can definitely help you in that matter. Since your codebase will be more and more buggy, refactoring is a necessity and these tools can shows you where to start. On a daily basis, they can give you good advice on all these little things you need to take care of to keep your codebase healthy.

Keep in mind though: they are a good complement but not a replacement for a solid test suite, beginning by good unit tests.

Do you use other tools than the one described here? Do you use them differently? Don’t hesitate to help the community by sharing your experience.

Conclusion

Let us know your thoughts in the comment section below.

Check out other publications to gain access to more digital resources if you are just starting out with Flux Resource.
Also contact us today to optimize your business(s)/Brand(s) for Search Engines

Leave a Reply

Flux Resource Help Chat
Send via WhatsApp