Learn from your fellow PHP developers with our PHP blogs, or help share the knowledge you've gained by writing your own.
$ composer require monolog/monolog
$ composer require monolog/monolog:1.18.0
$ composer require monolog/monolog:>1.18.0
$ composer require monolog/monolog:~1.18.0
$ composer require monolog/monolog:^1.18.0
$ composer global require "phpunit/phpunit:^5.3.*"
$ composer update
$ composer update monolog/monolog
4: Don’t install dev dependencies
In a lot of projects I am working on, I want to make sure that the libraries I download and install are working before I start working with them. To this end, many packages will include things like Unit Tests and documentation. This way I can run the unit Tests on my own to validate the package first. This is all fine and good, except when I don’t want them. There are times when I know the package well enough, or have used it enough, to not have to bother with any of that.5: Optimize your autoload
Regardless of whether you --prefer-dist or --prefer-source, when your package is incorporated into your project with require, it just adds it to the end of your autoloader. This isn’t always the best solution. Therefore Composer gives us the option to optimize the autoloader with the --optimize switch. Optimizing your autoloader converts your entire autoloader into classmaps. Instead of the autoloader having to use file_exists() to locate a file, Composer creates an array of file locations for each class. This can speed up your application by as much as 30%.$ composer dump-autoload --optimize
$ composer require monolog/monolog:~1.18.0 -o
CREATE TABLE <code>mydbname</code>.<code>content</code> ( <code>ID</code> INT(11) NOT NULL AUTO_INCREMENT , <code>title</code> VARCHAR(100) NOT NULL , <code>content</code> LONGTEXT NOT NULL , <code>author</code> VARCHAR(50) NOT NULL , PRIMARY KEY (<code>ID</code>)) ENGINE = MyISAM COMMENT = 'content table';
conn.php
file in your root/includes folder.conn.php
file, remember to include your own database credentials.
<?php
$letsconnect = new mysqli("localhost","dbuser","dbpass","dbname");
?>
index.php
at the root of your CMS folder.
<?php
include('includes/conn.php');
if ($letsconnect -> connect_errno) { echo "Error " . $letsconnect -> connect_error;
}else{
$getmydata=$letsconnect -> query("SELECT * FROM content");
foreach($getmydata as $mydata){ echo "Title: "; echo $mydata['title']; echo "<br/>"; echo "Content: "; echo $mydata['content']; echo "<br/>"; echo "Author: "; echo $mydata['author']; echo "<br/>"; echo "<br/>";
}
}
$letsconnect -> close();
?>
index.php
in your backend folder.
<html>
<head><title>Backend - Capture Content</title></head>
<body>
<form action="<?php $_SERVER[‘PHP_SELF’];?>" method="post">
<input type="text" name="title" placeholder="Content Title here" required/>
<textarea name="content">Content Here</textarea>
<input type="text" name="author" placeholder="Author" required/>
<input type="submit" value="Save My Data" name="savedata"/>
</form>
</body>
</html>
<form>
tag.
<?php
if(isset($_POST['savedata'])){
include('../includes/conn.php');
if ($letsconnect->connect_error) {
die("Your Connection failed: " . $letsconnect->connect_error);
}else{
$sql = "INSERT INTO content(title,content,author)VALUES ('".$_POST["title"]."', '".$_POST["content"]."', '".$_POST["author"]."')";
if (mysqli_query($letsconnect, $sql)) {
echo "Your data was saved successfully!";
} else { echo "Error: " . $sql . "" . mysqli_error($letsconnect);
} $letsconnect->close();
}
}
?>
Note, this is a basic MySQL query to insert data. However, before using this in production it's important to add proper escaping and security to prevent SQL injections. This will be covered in the next article.
composer create-project laravel/laravel ci-showcase
Next, I went to gitlab website and created a new public project: https://gitlab.com/crocodile2u/ci-showcase. Cloned the repo and copied all files and folders from the newly created project - the the new git repo. In the root folder, I placed a .gitignore
file:.idea
vendor
.env
Then the .env
file:APP_ENV=development
Then I generated the application encryption key: php artisan key:generate
, and then I wanted to verify that the primary setup works as expected: ./vendor/bin/phpunit
, which produced the output OK (2 tests, 2 assertions)
. Nice, time to commit this: git commit && git push
At this point, we don't yet have any CI, let's do something about it!php -l my-file.php
. This is what we're going to use. Because the php -l
command doesn't support multiple files as arguments, I've written a small wrapper shell script and saved it to ci/linter.sh
:#!/bin/sh
files=<code>sh ci/get-changed-php-files.sh | xargs</code>last_status=0
status=0
# Loop through changed PHP files and run php -l on each
for f in "$files" ; do message=<code>php -l $f</code> last_status="$?" if [ "$last_status" -ne "0" ]; then # Anything fails -> the whole thing fails echo "PHP Linter is not happy about $f: $message" status="$last_status" fi
done
if [ "$status" -ne "0" ]; then echo "PHP syntax validation failed!"
fi
exit $status
Most of the time, you don't actually want to check each and every PHP file that you have. Instead, it's better to check only those files that have been changed. The Gitlab pipeline runs on every push to the repository, and there is a way to know which PHP files have been changed. Here's a simple script, meet ci/get-changed-php-files.sh
:#!/bin/sh
# What's happening here?
#
# 1. We get names and statuses of files that differ in current branch from their state in origin/master.
# These come in form (multiline)
# 2. The output from git diff is filtered by unix grep utility, we only need files with names ending in .php
# 3. One more filter: filter *out* (grep -v) all lines starting with R or D.
# D means "deleted", R means "renamed"
# 4. The filtered status-name list is passed on to awk command, which is instructed to take only the 2nd part
# of every line, thus just the filename
git diff --name-status origin/master | grep '\.php$' | grep -v "^[RD]" | awk '{ print }'
These scripts can easily be tested in your local environment ( at least if you have a Linux machine, that is ;-) )..gitlab-ci.yml
. This is where your pipeline is declared using YAML notation:# we're using this beautiful tool for our pipeline: https://github.com/jakzal/phpqa
image: jakzal/phpqa:alpine
# For this sample pipeline, we'll only have 1 stage, in real-world you would like to also add at least "deploy"
stages: - QA
linter:
stage: QA
# this is the main part: what is actually executed
script: - sh ci/get-changed-php-files.sh | xargs sh ci/linter.sh
The first line is image: jakzal/phpqa:alpine
and it's telling Gitlab that we want to run our pipeline using a PHP-QA utility by jakzal. It is a docker image containing PHP and a huge variety of QA-tools. We declare one stage - QA, and this stage by now has just a single job named linter
. Every job can have it's own docker image, but we don't need that for the purpose of this tutorial. Our project reaches Step 2. Once I had pushed these changes, I immediately went to the project's CI/CD page. Aaaand.... the pipeline was already running! I clicked on the linter
job and saw the following happy green output:Running with gitlab-runner 11.9.0-rc2 (227934c0) on docker-auto-scale ed2dce3a
Using Docker executor with image jakzal/phpqa:alpine ...
Pulling docker image jakzal/phpqa:alpine ...
Using docker image sha256:12bab06185e59387a4bf9f6054e0de9e0d5394ef6400718332c272be8956218f for jakzal/phpqa:alpine ...
Running on runner-ed2dce3a-project-11318734-concurrent-0 via runner-ed2dce3a-srm-1552606379-07370f92...
Initialized empty Git repository in /builds/crocodile2u/ci-showcase/.git/
Fetching changes...
Created fresh repository.
From https://gitlab.com/crocodile2u/ci-showcase * [new branch] master -> origin/master * [new branch] step-1 -> origin/step-1 * [new branch] step-2 -> origin/step-2
Checking out 1651a4e3 as step-2...
Skipping Git submodules setup
$ sh ci/get-changed-php-files.sh | xargs sh ci/linter.sh
Job succeeded
It means that our pipeline was successfully created and run!phpcs.xml
:<?xml version="1.0"?>
/resources
I also will append another section to .gitlab-ci.yml
:code-style: stage: QA script: # Variable $files will contain the list of PHP files that have changes - files=<code>sh ci/get-changed-php-files.sh</code> # If this list is not empty, we execute the phpcs command on all of them - if [ ! -z "$files" ]; then echo $files | xargs phpcs; fi
Again, we check only those PHP files that differ from master branch, and pass their names to phpcs
utility. That's it, Step 3 is finished! If you go to see the pipeline now, you will notice that linter
and code-style
jobs run in parallel.vendor
folder with composer. You might have noticed that our .gitignore
file has vendor
folder as one of it entries, which means that it is not managed by the Version Control System. Some prefer their dependencies to be part of their Git repository, I prefer to have only the composer.json
declarations in Git. Makes the repo much much smaller than the other way round, also makes it easy to avoid bloating your production builds with libraries only needed for development..gitlab-ci.yml
:test: stage: QA cache: key: dependencies-including-dev paths: - vendor/ script: - composer install - ./vendor/bin/phpunit
PHPUnit requires some configuration, but in the very beginning we used composer create-project
to create our project boilerplate.laravel/laravel package has a lot of things included in it, and phpunit.xml
is also one of them. All I had to do was to add another line to it:xml
APP_KEY enironment variable is essential for Laravel to run, so I generated a key with php artisan key:generate
.git commit
& git push
, and we have all three jobs on theQA stage!$ ci/linter.sh
PHP Linter is not happy about app/User.php:
Parse error: syntax error, unexpected 'syntax' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) in app/User.php on line 11
Errors parsing app/User.php
PHP syntax validation failed!
ERROR: Job failed: exit code 255
**Code-style**:$ if [ ! -z "$files" ]; then echo $files | xargs phpcs; fi
FILE: ...ilds/crocodile2u/ci-showcase/app/Http/Controllers/Controller.php
----------------------------------------------------------------------
FOUND 0 ERRORS AND 1 WARNING AFFECTING 1 LINE
---------------------------------------------------------------------- 13 | WARNING | Line exceeds 120 characters; contains 129 characters
----------------------------------------------------------------------
Time: 39ms; Memory: 6MB
ERROR: Job failed: exit code 123
**test**:$ ./vendor/bin/phpunit
PHPUnit 7.5.6 by Sebastian Bergmann and contributors.
F. 2 / 2 (100%)
Time: 102 ms, Memory: 14.00 MB
There was 1 failure:
1) Tests\Unit\ExampleTest::testBasicTest
This test is now failing
Failed asserting that false is true.
/builds/crocodile2u/ci-showcase/tests/Unit/ExampleTest.php:17
FAILURES!
Tests: 2, Assertions: 2, Failures: 1.
ERROR: Job failed: exit code 1
Congratulations, our pipeline is running, and we now have much less chance of messing up the result of our work.