DEV Community

Benjamin Delespierre
Benjamin Delespierre

Posted on

Package Artisan commands in 5 minutes

A while ago, I wrote a Laravel command that validates Blade templates in order to become part of my continuous integration pipeline.

It just compiles the given Blade templates and then uses the PHP internal linter to validate them.

Yesterday, someone just asked me if I planned to distribute it as a standalone phar archive.

I thought it would be interesting so here's how I did it.

First, make a standalone executable

Laravel Blade Linter is distributed as a Laravel package and is intended to be run as follow:

php artisan blade:lint <files>
Enter fullscreen mode Exit fullscreen mode

Since it's an Artisan command, it cannot run outside of a Laravel project...

Or can it?

Turns out Artisan commands are built on top of Symfony console, so you can start them like this:

// create the Symfony console application
$application = new Application();
$application->add(new BladeLinterCommand);
$application->run();
Enter fullscreen mode Exit fullscreen mode

But the command leverage Laravel's services, so we need to provide them to it:

// create an empty container
$laravel = new Container();

$laravel['config'] = fn() => new Config([
    // use current directory as view path
    'view.paths' => getcwd(),

    // send compiled views to /tmp
    'view.compiled' => sys_get_temp_dir(),
]);

// register services the command needs
(new FilesystemServiceProvider($laravel))->register();
(new ViewServiceProvider($laravel))->register();

// set the container so the Config::get calls resolve
Facade::setFacadeApplication($laravel);

// prepare the command
$command = new BladeLinterCommand();
$command->setLaravel($laravel);
Enter fullscreen mode Exit fullscreen mode

And now it runs properly inside its Symfony application shell!

# now the command can run outside of Laravel!
bin/blade-linter <files>
Enter fullscreen mode Exit fullscreen mode

The final script is available here.

Time to package it

Building a phar archive is easier than I thought it would be. All you need is phar-composer.

# install phar-composer globally
composer global require clue/phar-composer
Enter fullscreen mode Exit fullscreen mode

Then register the executable we made above in composer.json:

{
    "bin": [
        "bin/blade-linter"
    ]
}
Enter fullscreen mode Exit fullscreen mode

Now we can build the phar:

phar-composer build ./
Enter fullscreen mode Exit fullscreen mode

The result is an executable archive that can be distributed as a standalone application.

$ laravel-blade-linter.phar lint tests/views/
PHP Parse error:  syntax error, unexpected ')' in tests/views/invalid.blade.php on line 1
Enter fullscreen mode Exit fullscreen mode

And voilà


Don't forget to leave a like and tell me in the comments what you think of this article.


From the same author:

Top comments (0)