WordPress MVC (WPMVC) flexibility allows developers to extend the capabilities of the build process by adding a custom task that will minify PHP files.

Minifying PHP files can add a tiny layer of security for those projects which are not open source.

This article will describe shortly how to configure your WordPress MVC project to minify all the PHP files located under the path /app.


Requirements

  • PHP: Needs to be installed and accessible via command line.

Step 1: Install dependencies

The following command will install @aquafadas/gulp-php-minify package in your project and save it as dependency:

npm install @aquafadas/gulp-php-minify --save

Step 2: Modify gulpfile.js

You need to modify your gulpfile.js in order to register @aquafadas/gulp-php-minify and to add custom tasks for less compilations.

Require phpMinify

At the beginning of the file add this line:

var phpMinify = require('@aquafadas/gulp-php-minify');

The line above, will make the package is registered and loaded.

Custom tasks

You will create two tasks:

  • pre-phpmin: This task will delete from the /builds/staging path all the files to be minified.
  • phpmin: This task will copy and minify all PHP files located at /app.

The phpmin task needs to be included in WordPress MVC compilation cycle. To do this, we will modify the configuration’s minify step, to make sure your custom task is included.

// --------------
// START - CUSTOM TASKS

config.minify = ['cssmin', 'jsmin', 'phpmin'];

The modification above indicates that cssmin, jsmin and phpmin should be required. This will enable WPMVC cycle to minify CSS, Javascript and PHP files.

Following the line above, add the following:

// pre-phpmin task
gulp.task('pre-phpmin', function () {
    return del([
        './builds/staging/'+config.name+'/app/**/*',
        './builds/staging/'+config.name+'/app/',
    ]);
});

// phpmin task
gulp.task('phpmin', gulp.series('pre-phpmin', function () {
    return gulp.src('./app/**/*.php', {read: false})
        .pipe(phpMinify({binary: 'drive:\\path-to\\php.exe', silent: true}))
        .pipe(gulp.dest('./builds/staging/'+config.name+'/app/'));
}));

The snippet above will add tasks pre-phpmin and phpmin. php-min is will run before phpmin.

The string drive:\path-to\php.exe needs to be replaced with your PHP’s location path and filename.


Step 3: Compile

With gulpfile.js modified, you can compile, build and minify your assets by running the command:

gulp build

Or for special CI/CD deployments:

gulp deploy