23 min read
Next in trending

Laravel 4 Deployment

A Comprehensive Tutorial

Laravel 4 Deployment

A Comprehensive Tutorial


Introduction

Laravel 4 is a huge step forward for the PHP community. It’s beautifully written, full of features and the community is presently exploding. It’s with this in mind that I would like to show how to deploy Laravel 4 applications, using Artisan.

I have spent two full hours getting the code out of a Markdown document and into Medium. Medium really isn’t designed for tutorials such as this, and while much effort has been spent in the pursuit of accuracy; there’s a good chance you could stumble across a curly quote in a code listing. Please make a note and I will fix where needed.
I have also uploaded this code to Github. You need simply follow the configuration instructions in this tutorial, after downloading the source code, and the application should run fine. This assumes, of course, that you know how to do that sort of thing. If not; this shouldn’t be the first place you learn about making PHP applications.
https://github.com/formativ/tutorial-laravel-4-deployment
If you spot differences between this tutorial and that source code, please raise it here or as a GitHub issue. Your help is greatly appreciated.

A Note On Subjectivity

Deployment processes are one of the most subjective things about development. Everyone’s got their own ideas about what should and shouldn’t be done. There are sometimes best practises; though these tend only to apply to subsets of the whole process.

Things get even more tricky when it comes to deploying Laravel 4 applications because there aren’t really any best practises to speak of. Due to its subjective nature; it’s not covered in the documentation, and it’s also a relatively new topic.

Remember this as you continue — this tutorial isn’t the only approach to deploying Laravel 4 applications. It’s simply a process I’ve found works for me.

Installing Laravel 4

Laravel 4 uses Composer to manage its dependencies. You can install Composer by following the instructions at http://getcomposer.org/doc/
00-intro.md#installation-nix
.

Once you have Composer working, make a new directory or navigation to an existing directory and install Laravel 4 with the following command:

composer create-project laravel/laravel ./ --prefer-dist

If you chose not to install Composer globally (though you really should), then the command you use should resemble the following:

php composer.phar create-project laravel/laravel ./ --prefer-dist

Both of these commands will start the process of installing Laravel 4. There are many dependencies to be sourced and downloaded; so this process may take some time to finish.

Installing Other Dependencies

Our deployment processes will need to handle JavaScript and CSS files. Assetic is an asset management library which we will use to do all the heavy lifting in this area.

To install it; we need to add two requirements to our composer.json file:

"kriswallsmith/assetic"   : "1.2.*@dev",
"toopay/assetic-minifier" : "dev-master"
This was extracted from composer.json for brevity.

Lastly, we will also be using Jason Lewis’ Resource Watcher library, which integrates with Laravel 4's Filesystem classes to enable notification of file changes. You’ll see why that’s useful in a bit…

"jasonlewis/resource-watcher" : "dev-master"
This was extracted from composer.json for brevity.

Once these requirements are added to the composer.json file, we need to update the vendor folder:

composer update

We’ll look at how to integrate these into our deployment workflow shortly.

Setting Environments

Environments are a small, yet powerful, aspect of any Laravel 4 application. They primarily allow the specification of machine-based configuration options.

There are a few things you need to know about environments, in Laravel 4:

  1. The files contained in the root of app/config are merged or overridden by environment-based configuration files.
  2. Configuration files that are specific to an environment are stored in folders matching their environment name.
  3. Environments are determined by an array specified in bootstrap/start.php and are matched according to the name of the machine on which the application is being run.
  4. An application can have any number of environments; each with their own configuration files. There can also be multiple machine names (hosts) in each environment. You can have two staging servers, a production server and a testing server (for instance). If their machine names match those in bootstrap/start.php then their individual configuration files will be loaded.
  5. All Artisan commands can be given an --env option which will override the environment settings of the machine on which the commands are run.

I’m sure there are other ways in which environments affect application execution, but you get the point: environments are a big-little thing.

Managing Environments

As I mentioned earlier; environments are usually specified in boostrap/start.php. This is probably going to be ok for the 99% of Laravel 4 applications that will ever be made, but we can improve upon it slightly still.

We’re going to make the list of environments somewhat dynamic, and load them in a slightly different way to how they are loaded out-the-box.

The first thing we’re going to do is learn how to make a command to tell us what the current environment is. Commands are the Laravel 4 way of extending the power and functionality of the Artisan command line tool. There are some commands already available when installing Laravel 4 (and we’ve seen some of them already, in previous tutorials).

To make our own, we can use an Artisan command:

php artisan command:make FooCommand

This command will make a new file at app/commands/FooCommand
.php
. Inside this file you will begin to see what commands look like under the hood. Here’s an example of the file that gets generated:

<?php
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class FooCommand extends Command {
    /**
* The console command name.
*
* @var string
*/
protected $name = 'command:name';
    /**
* The console command description.
*
* @var string
*/
protected $description = 'Command description.';
    /**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
    /**
* Execute the console command.
*
* @return void
*/
public function fire()
{
//
}
    /**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array(
array(
'example',
InputArgument::REQUIRED,
'An example argument.'
),
);
}
    /**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return array(
array(
'example',
null,
InputOption::VALUE_OPTIONAL,
'An example option.',
null
),
);
}
}
This file should be saved as app/commands/FooCommand.php.

There are a few things of importance here:

  1. The $name property is used both to describe the command as well as invoke it. If we change it to foo, and register it correctly (as we’ll do in a moment), then we would be able to call it with: php artisan foo
  2. The description property is only descriptive. When all the registered command are displayed (by a call to: php artisan) then this description will be shown next to the name of the command.
  3. The fire() method is where all the action happens. If you want your command to do anything; there is where it needs to get done.
  4. The getArguments() method should return an array of arguments (or parameters) to the command. If our command was: php artisan foo bar, then bar would be an argument. Arguments are named (which we will see shortly).
  5. the getOptions() method should return an array of options (or flags) to the command. If out command was: php artisan foo --baz, then --baz would be an option. Options are also named (which we will also see shortly).

This file gives us a good starting point from which to build our own set of commands.

We begin our commands by creating the EnvironmentCommand class:

<?php
use Illuminate\Console\Command;
class EnvironmentCommand
extends Command
{
protected $name = "environment";
    protected $description = "Lists environment commands.";
    public function fire()
{
$this->line(trim("
<comment>environment:get</comment>
<info>gets host and environment.</info>
"));
        $this->line(trim("
<comment>environment:set</comment>
<info>adds host to environment.</info>
"));
        $this->line(trim("
<comment>environment:remove</comment>
<info>removes host from environment.</info>
"));
}
    protected function getArguments()
{
return [];
}
    protected function getOptions()
{
return [];
}
}
This file should be saved as app/commands/EnvironmentCommand.php.

The command class begins with us setting a useful name and description for the following commands we will create. The fire() method includes three calls to the line() method; which prints text to the command line. The getArguments() and getOptions() methods return empty arrays because we do not expect to handle any arguments or options.

You may have noticed the XML notation within the calls to the line() method. Laravel 4's console library extends Symphony 2's console library; and Symphony 2's console library allows these definitions in order to alter the meaning and appearance of text rendered to the console.
While the appearance will be changed, by using this notation, it’s not the best thing to be doing (semantically speaking). The bits in the comment elements aren’t comments any more than the bit in the info elements are.
We’re simply using it for a refreshing variation in the console text colours.
If this sort of jacky behaviour offends your senses, feel free to omit the XML notation altogether!

Before we can run any commands; we need to register them with Artisan:

Artisan::add(new EnvironmentCommand);
This was extracted from app/start/artisan.php for brevity.

There’s nothing much more to say than; this code registers the command with Artisan, so that it can be invoked. We should be able to call the command now, and it should show us something like the following:

❯ php artisan environment
environment:get gets host and environment.
environment:set adds host to environment.
environment:remove removes host from environment.

Congratulations! We’ve successfully created and registered our first Artisan command. Let’s go ahead and make a few more.

To make the first described command (environment:get); we’re going to subclass the EnvironmentCommand class we just created. We’ll be adding reusable code in the EnvironmentCommand class so it’s a means of accessing this code in related commands.

<?php
use Illuminate\Console\Command;
class EnvironmentGetCommand
extends EnvironmentCommand
{
protected $name = "environment:get";
    protected $description = "Gets host and environment.";
    public function fire()
{
$this->line(trim("
<comment>Host:</comment>
<info>" . $this->getHost() . "</info>
"));
        $this->line(trim("
<comment>Environment:</comment>
<info>" . $this->getEnvironment() . "</info>
"));
}
}
This file should be saved as app/commands/EnvironmentGetCommand.php.

The EnvironmentGetCommand does slightly more than the previous command we made. It fetches the host name and the environment name from functions we must define in the EnvironmentCommand class:

protected function getHost()
{
return gethostname();
}
protected function getEnvironment()
{
return App::environment();
}
This was extracted from app/commands/EnvironmentCommand.php for brevity.

The gethostname() function returns the name of the machine on which it is invoked. Similarly; the App::environment() method returns the name of the environment in which Laravel is being run.

After registering and running this command, I see the following:

❯ php artisan environment:get
Host: formativ.local
Environment: local

The next command is going to allow us to alter these values from the command line (without changing hard-coded values)…

<?php
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
class EnvironmentSetCommand
extends EnvironmentCommand
{
protected $name = "environment:set";
    protected $description = "Adds host to environment.";
    public function fire()
{
$host = $this->getHost();
$config = $this->getConfig();
$overwrite = $this->option("host");
$environment = $this->argument("environment");
        if (!isset($config[$environment]))
{
$config[$environment] = [];
}
        $use = $host;
        if ($overwrite)
{
$use = $overwrite;
}
        if (!in_array($use, $config[$environment]))
{
$config[$environment][] = $use;
}
        $this->setConfig($config);
        $this->line(trim("
<info>Added</info>
<comment>" . $use . "</comment>
<info>to</info>
<comment>" . $environment . "</comment>
<info>environment.</info>
"));
}
    protected function getArguments()
{
return [
[
"environment",
InputArgument::REQUIRED,
"Environment to add the host to."
]
];
}
    protected function getOptions()
{
return [
[
"host",
null,
InputOption::VALUE_OPTIONAL,
"Host to add.",
null
]
];
}
}
This file should be saved as app/commands/EnvironmentSetCommand.php.

The EnvironmentSetCommand class’ fire() method begins by getting the host name and a configuration array (using inherited methods). It also checks for a host option and an environment argument.

If the host option is provided; it will be added to the list of hosts for the provided environment. If no host option is provided; it will default to the machine the code is being executed on.

We also need to add the inherited methods to the EnvironmentCommand class:

protected function getHost()
{
return gethostname();
}
protected function getEnvironment()
{
return App::environment();
}
protected function getPath()
{
return app_path() . "/config/environment.php";
}
protected function getConfig()
{
$environments = require $this->getPath();
    if (!is_array($environments))
{
$environments = [];
}
    return $environments;
}
protected function setConfig($config)
{
$config = "<?php return " . var_export($config, true) . ";";
File::put($this->getPath(), $config);
}
This was extracted from app/commands/EnvironmentCommand.php for brevity.

The getConfig() method fetches the contents of the app/config/
environment.php
file (a list of hosts per environment) and the setConfig() method writes back to it. We use the var_export() to re-create the array that’s stored in memory; but it’s possible to get a more aesthetically-pleasing configuration file. I’ve customised the setConfig() method to match my personal taste:

protected function setConfig($config)
{
$code = "<?php\n\nreturn [";
    foreach ($config as $environment => $hosts)
{
$code .= "\n \"" . $environment . "\" => [";
        foreach ($hosts as $host)
{
$code .= "\n \"" . $host . "\",";
}
        $code = trim($code, ",");
$code .= "\n ],";
}
    $code = trim($code, ",");
File::put($this->getPath(), $code . "\n];");
}
This was extracted from app/commands/EnvironmentCommand.php for brevity.

In order for these environments to be of any use to us; we need to replace those defined in bootstrap/start.php with the following lines:

$env = $app->detectEnvironment(
require __DIR__ . "/../app/config/environment.php"
);
This was extracted from bootstrap/start.php for brevity.

This ensures that the environments we set (using our environment commands), and not those hard-coded in the bootstrap/start.php file are used in determining the current machine environment.

The last environment command we will create will provide us a way to remove hosts from an environment (in much the same way as they were added):

<?php
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
class EnvironmentRemoveCommand
extends EnvironmentCommand
{
protected $name = "environment:remove";
    protected $description = "Removes host from environment.";
    public function fire()
{
$host = $this->getHost();
$config = $this->getConfig();
$overwrite = $this->option("host");
$environment = $this->argument("environment");
        if (!isset($config[$environment]))
{
$config[$environment] = [];
}
        $use = $host;
        if ($overwrite)
{
$use = $overwrite;
}
        foreach ($config[$environment] as $index => $item)
{
if ($item == $use)
{
unset($config[$environment][$index]);
}
}
        $this->setConfig($config);
        $this->line(trim("
<info>Removed</info>
<comment>" . $use . "</comment>
<info>from</info>
<comment>" . $environment . "</comment>
<info>environment.</info>
"));
}
    protected function getArguments()
{
return [
[
"environment",
InputArgument::REQUIRED,
"Environment to remove the host from."
]
];
}
    protected function getOptions()
{
return [
[
"host",
null,
InputOption::VALUE_OPTIONAL,
"Host to remove.",
null
]
];
}
}
This file should be saved as app/commands/EnvironmentRemoveCommand.php.

It’s pretty much the same as the EnvironmentSetCommand class, but instead of adding them to the configuration file; we remove them from the configuration file. It uses the same formatter as the EnvironmentSetCommand class.

Commands make up a lot of this tutorial. It may, therefore, surprise you to know that there’s not much more to them than this. Sure, there are different types (and values) of InputOption’s and InputArgument’s, but we’re not going into that level of detail here.
You can find out more about these at: http://symfony.com/doc/current/
components/console/introduction.html

Managing Assets

There are two parts to managing assets. The first is how they are stored and referenced in views, and the second is how they are combined/minified.

Both of these operations will require a sane method of specifying asset containers and the assets contained therein. For this; we will create a new configuration file (in each environment we will be using):

<?php
return [
"header-css" => [
"css/bootstrap.css",
"css/shared.css"
],
"footer-js" => [
"js/jquery.js",
"js/bootstrap.js",
"js/shared.js"
]
];
This file should be saved as app/config/local/asset.php.
<?php
return [
"header-css" => [
"css/shared.min.css" => [
"css/bootstrap.css",
"css/shared.css"
]
],
"footer-js" => [
"js/shared.min.js" => [
"js/jquery.js",
"js/bootstrap.js",
"js/shared.js"
]
]
];
This file should be saved as app/config/production/asset.php.

The difference between these environment-based asset configuration files is how the files are combined in the production environment vs. how they are simply listed in the local environment. This makes development easier because you can see unaltered files while still developing and testing; while the production environment will have smaller file sizes.

To use these in our views; we’re going to make a form macro. It’s not technically what form macros were made for (since we’re not using them to make forms) but it’s such a convenient/clean method for generating view markup that we’re going to use it anyway.

<?php
Form::macro("assets", function($section)
{
$markup = "";
$assets = Config::get("asset");
    if (isset($assets[$section]))
{
foreach ($assets[$section] as $key => $value)
{
$use = $value;
            if (is_string($key))
{
$use = $key;
}
            if (ends_with($use, ".css"))
{
$markup .= "<link
rel='stylesheet'
type='text/css'
href='" . asset($use) . "'
/>";
}
            if (ends_with($use, ".js"))
{
$markup .= "<script
type='text/javascript'
src='" . asset($use) . "'
></script>";
}
}
}
    return $markup;
});
This file should be saved as app/macros.php.

This macro accepts a single parameter — the name of the section — and renders HTML markup elements for each asset file. It doesn’t matter if there are a combination of stylesheets and scripts as the applicable tag is rendered for each asset type.

We also need to make sure this file gets included in our application’s startup processes:

require app_path() . "/macros.php";
This was extracted from app/start/global.php for brevity.

We can now use this in our templates…

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Laravel 4 — Deployment Tutorial</title>
{{ Form::assets("header-css") }}
</head>
<body>
<h1>Hello World!</h1>
{{ Form::assets("footer-js") }}
</body>
</html>
This file should be saved as app/views/hello.blade.php.

Now, depending on the environment we have set; we will either see a list of asset files in each section, or single (production) asset files.

You will notice the difference by changing your environment from local to production. Give the environment commands a go — this is the kind of thing they were made for!

Combining

The simplest asset operation is combining. This is where we put two or more stylesheets or scripts together into a single file. Similarly to how we arranged the environment classes; the asset commands will inherit form a master command:

<?php
use Assetic\Asset\AssetCollection;
use Assetic\Asset\FileAsset;
use Illuminate\Console\Command;
class AssetCommand
extends Command
{
protected $name = "asset";
    protected $description = "Lists asset commands.";
    public function fire()
{
$this->line(trim("
<comment>asset:combine</comment>
<info>combines resource files.</info>
"));
        $this->line(trim("
<comment>asset:minify</comment>
<info>minifies resource files.</info>
"));
}
    protected function getArguments()
{
return [];
}
    protected function getOptions()
{
return [];
}
    protected function getPath()
{
return public_path();
}
    protected function getCollection($input, $filters = [])
{
$path = $this->getPath();
$input = explode(",", $input);
$collection = new AssetCollection([], $filters);
        foreach ($input as $asset)
{
$collection->add(
new FileAsset($path . "/" . $asset)
);
}
        return $collection;
}
    protected function setOutput($file, $content)
{
$path = $this->getPath();
return File::put($path . "/" . $file, $content);
}
}
This file should be saved as app/commands/AssetCommand.php.

Here’s where we make use of Assetic. Among the many utilities Assetic provides; the AssetCollection and FileAsset classes will be out main focus. The getCollection() method accepts a comma-delimited list of asset files (relative to the public folder) and returns a populated AssetCollection instance.

<?php
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
class AssetCombineCommand
extends AssetCommand
{
protected $name = "asset:combine";
    protected $description = "Combines resource files.";
    public function fire()
{
$input = $this->argument("input");
$output = $this->option("output");
$combined = $this->getCollection($input)->dump();
        if ($output)
{
$this->line(trim("
<info>Successfully combined</info>
<comment>" . $input . "</comment>
<info>to</info>
<comment>" . $output . "</comment>
<info>.</info>
"));
            $this->setOutput($output, $combined);
}
else
{
$this->line($combined);
}
}
    protected function getArguments()
{
return [
[
"input",
InputArgument::REQUIRED,
"Names of input files."
]
];
}
    protected function getOptions()
{
return [
[
"output",
null,
InputOption::VALUE_OPTIONAL,
"Name of output file.",
null
]
];
}
}
This file should be saved as app/commands/AssetCombineCommand.php.

The AssetCombineCommand class expects the aforementioned list of assets and will output the results to console, by default. If we want to save the results to a file we can provide the —output option with a path to the combined file.

You can learn more about Assetic at: https://github.com/kriswallsmith/
assetic/

Minifying

Minifying asset files is just as easy; thanks to the Assetic-Minifier filters. Assetic provides filters which can be used to transform the output of asset files.

Usually some of these filters depend on third-party software being installed on the server, or things like Java applets. Fortunately, the Assetic-Minifier library provides pure PHP alternatives to CssMin and JSMin filters (which would otherwise need additional software installed).

<?php
use Minifier\MinFilter;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
class AssetMinifyCommand
extends AssetCommand
{
protected $name = "asset:minify";
    protected $description = "Minifies resource files.";
    public function fire()
{
$type = $this->argument("type");
$input = $this->argument("input");
$output = $this->option("output");
$filters = [];
        if ($type == "css")
{
$filters[] = new MinFilter("css");
}
        if ($type == "js")
{
$filters[] = new MinFilter("js");
}
        $collection = $this->getCollection($input, $filters);
$combined = $collection->dump();
        if ($output)
{
$this->line(trim("
<info>Successfully minified</info>
<comment>" . $input . "</comment>
<info>to</info>
<comment>" . $output . "</comment>
<info>.</info>
"));
            $this->setOutput($output, $combined);
}
else
{
$this->line($combined);
}
}
    protected function getArguments()
{
return [
[
"type",
InputArgument::REQUIRED,
"Code type."
],
[
"input",
InputArgument::REQUIRED,
"Names of input files."
]
];
}
    protected function getOptions()
{
return [
[
"output",
null,
InputOption::VALUE_OPTIONAL,
"Name of output file.",
null
]
];
}
}
This file should be saved as app/commands/AssetMinifyCommand.php.

The minify command accepts two arguments — the type of assets (either css or js) and the comma-delimited list of asset files to minify. Like the combine command; it will output to console by default, unless the —output option is specified.

You can learn more about Assetic-Minifier at: https://github.com/toopay/
assetic-minifier

Building

Commands that accept inputs and outputs are really useful for the combining and minifying asset files, but it’s a pain to have to specify inputs and outputs each time (especially when we have gone to the effort of defining asset lists in configuration files). For this purpose; we need a command which will combine and minify all the asset files appropriately.

<?php
use Illuminate\Console\Command;
class BuildCommand
extends Command
{
protected $name = "build";
    protected $description = "Builds resource files.";
    public function fire()
{
$sections = Config::get("asset");
        foreach ($sections as $section => $assets)
{
foreach ($assets as $output => $input)
{
if (!is_string($output))
{
continue;
}
                if (!is_array($input))
{
$input = [$input];
}
                $input = join(",", $input);
                $options = [
"--output" => $output,
"input" => $input
];
                if (ends_with($output, ".min.css"))
{
$options["type"] = "css";
$this->call("asset:minify", $options);
}
else if (ends_with($output, ".min.js"))
{
$options["type"] = "js";
$this->call("asset:minify", $options);
}
else
{
$this->call("asset:combine", $options);
}
}
}
}
}
This file should be saved as app/commands/BuildCommand.php.

The BuildCommand class fetches the asset lists, from the configuration files, and iterates over them; combining/minifying as needed. It does this by checking file extensions. If the file ends in .min.js then the minify command is run in js mode. Files ending in .min.css are minified in css mode, and so forth.

The app/config/*/asset.php files are environment-based. This means running the build command will build the assets for the current environment. Often this will not be the environment you want to build assets for. I often build assets on my local machine, yet I want assets built for production. When that is the case; I provide the --env=production flag to the build command.

Watching

So we have the tools to combine, minify and even build our asset files. It’s a pain to have to remember to do those things all the time (especially when files are being updated at a steady pace), so we’re going to take it a step further by adding a file watcher.

Remember the Resource Watcher library we added to composer.json? Well we need to add it to the list of service providers:

"providers" => [
// other service providers here
"JasonLewis\ResourceWatcher\Integration\LaravelServiceProvider"
]
This was extracted from app/config/app.php for brevity.

The Resource Watcher library requires Laravel 4's Filesystem library, and this service provider will allow us to utilise dependency injection.

<?php
use Illuminate\Console\Command;
class WatchCommand
extends Command
{
protected $name = "watch";
    protected $description = "Watches for file changes.";
    public function fire()
{
$path = $this->getPath();
$watcher = App::make("watcher");
$sections = Config::get("asset");
        foreach ($sections as $section => $assets)
{
foreach ($assets as $output => $input)
{
if (!is_string($output))
{
continue;
}
                if (!is_array($input))
{
$input = [$input];
}
                foreach ($input as $file)
{
$watch = $path . "/" . $file;
$listener = $watcher->watch($watch);
                    $listener->onModify(function() use (
$section,
$output,
$input,
$file
)
{
$this->build(
$section,
$output,
$input,
$file
);
});
}
}
}
        $watcher->startWatch();
}
    protected function build($section, $output, $input, $file)
{
$options = [
"--output" => $output,
"input" => join(",", $input)
];
         $this->line(trim("
<info>Rebuilding</info>
<comment>" . $output . "</comment>
<info>after change to</info>
<comment>" . $file . "</comment>
<info>.</info>
"));
         if (ends_with($output, ".min.css"))
{
$options["type"] = "css";
$this->call("asset:minify", $options);
}
else if (ends_with($output, ".min.js"))
{
$options["type"] = "js";
$this->call("asset:minify", $options);
}
else
{
$this->call("asset:combine", $options);
}
}
    protected function getArguments()
{
return [];
}
    protected function getOptions()
{
return [];
}
    protected function getPath()
{
return public_path();
}
}
This file should be saved as app/commands/WatchCommand.php.

The WatchCommand class is a step up from the BuildCommand class in that it processes asset files similarly. Where it excels is in how it is able to watch the individual files in app/config/*/asset.php.

When a Watcher targets a specific file (with the $watcher->watch() method); it generates a Listener. Listeners can have events bound to them (as is the case with the onModify() event listener method).

When these files change, the processed asset files they form part of are rebuilt, using the same logic as in the build command.

You have to have the watcher running in order for updates to cascade into combined/minified asset files. Do this by running: php artisan watch
You can learn more about the Resource Watcher library at: https://github.com/jasonlewis/resource-watcher

Resource Watcher Integration Bug

While creating this tutorial; I found a bug with the service provider. It relates to class resolution, and was probably caused by a reshuffling of the library. I have since contacted Jason Lewis to inform him of the bug, and submitted a pull request which resolves it.

This bug has been fixed!

Rsync

Rsync is a file synchronisation utility which we will use to synchronise our distribution folder to a remote server. It requires a valid private/public key and some configuration.

To set up SSH access, for your domain, follow these steps:

  1. Back up any keys you already have in ~/.ssh
  2. Generate a new key with: ssh-keygen -t rsa -C “your_email@example.com
  3. Remember the name you set here.
  4. Copy the contents of the new public key file (the name from step 3, ending in .pub).
  5. SSH into your remove server.
  6. Add the contents of the new public key file (which you copied in step 3) to ~/.ssh/authorized_keys.
  7. Add the following lines to ~/.ssh/config (on your local machine):
host example.com
User your_user
IdentityFile your_key_file
This was extracted from ~/.ssh/config for brevity.
The your_user account needs to be the same as the one with which you SSH’d into the remote server and added the authorised key.
The your_identity_file is the name from step 3 (not ending in .pub).

Now, when you type ssh example.com (where example.com is the name of the domain you’ve been accessing with SSH); you should be let in without even having to provide a password. Don’t worry — your server is still secure. You’ve just let it know (ahead of time) what an authentic connection from you looks like.

With this configuration in place; you won’t need to do anything tricky in order to get Rsync to work correctly. The hard part is getting a good connection…

Distributing

In order for us to distribute our code, we need to make a copy of it and perform some operations on the copy. This involves optimisation and cleanup.

Making A Copy

First, let’s make the copy command:

<?php
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
class CopyCommand
extends Command
{
protected $name = "copy";
    protected $description = "Creates distribution files.";
    public function fire()
{
$target = $this->option("target");
        if (!$target)
{
$target = "../distribution";
}
        File::copyDirectory("./", $target);
        $this->line(trim("
<info>Successfully copied source files to</info>
<comment>" . realpath($target) . "</comment>
<info>.</info>
"));
}
    protected function getArguments()
{
return [];
}
    protected function getOptions()
{
return [
[
"target",
null,
InputOption::VALUE_OPTIONAL,
"Distribution path.",
null
]
];
}
}
This file should be saved as app/commands/CopyCommand.php.

The copy command uses Laravel 4's File methods to copy the source directly recursively. It initially targets ../distribute but this can be changed with the --target option.

It’s important that you copy the distribution files to a target outside of your source folder. The copy command copies ./ which means a target inside will lead to an “infinite copy loop” where the command tries to copy the distribution folder into itself an infinite number of times.
To get around this; I guess you could target sources files individually (or in folders). It’s likely that you will be running the copy command from a local machine, so there’s little harm in copying the distribution files into a directory outside of the one your application files are in.

Cleaning The Copy

Next up, we need a command to remove any temporary/development files. We’ll start by creating a config file in which these files are listed:

<?php
return [
"app/storage/cache/*",
"app/storage/logs/*",
"app/storage/sessions/*",
"app/storage/views/*",
".DS_Store",
".git*",
".svn*",
"public/js/jquery.js",
"public/js/bootstrap.js",
"public/js/shared.js",
"public/css/bootstrap.css",
"public/css/shared.css"
];
This file should be saved as app/config/clean.php.

I’ve just listed a few common temporary/development files. You can use any syntax that works with PHP’s glob() function, as this is what Laravel 4 is using behind the scenes.

I’m also removing the development scripts and styles, as these will be built into minified asset files by the build command.

<?php
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
class CleanCommand
extends Command
{
protected $name = "clean";
    protected $description = "Cleans distribution folder.";
    public function fire()
{
$target = $this->option("target");
        if (!$target)
{
$target = "../distribution";
}
        $cleaned = Config::get("clean");
        foreach ($cleaned as $pattern)
{
$paths = File::glob($target . "/" . $pattern);
            foreach ($paths as $path)
{
if (File::isFile($path))
{
File::delete($path);
}
                if (File::isDirectory($path))
{
File::deleteDirectory($path);
}
}
            $this->line(trim("
<info>Deleted all files/folders matching</info>
<comment>" . $pattern . "</comment>
<info>.</info>
"));
}
}
    protected function getArguments()
{
return [];
}
    protected function getOptions()
{
return [
[
"target",
null,
InputOption::VALUE_OPTIONAL,
"Distribution path.",
null
]
];
}
}
This file should be saved as app/commands/CleanCommand.php.

The CleanCommand class gets all files matching the patterns in app/config/clean.php and deletes them. It handles folders as well.

Be very careful when deleting files. It’s always advisable to make a full backup before you test these kinds of scripts. I nearly nuked all the tutorial code because I didn’t make a backup!

Synching To The Remote Server

We’ve set up SSH access and we have code ready for deployment. Before we sync, we should set up a config file for target remote servers:

<?php
return [
"production" => [
"url" => "example.com",
"path" => "/var/www"
]
];
This file should be saved as app/config/host.php.

The normal SSH access we’ve set up takes care of the username and password, so all we need to be able to configure is the url of the remote server and the path on it to upload the files to.

<?php
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
class DistributeCommand
extends Command
{
protected $name = "distribute";
    protected $description = "Synchronises files with target.";
    public function fire()
{
$host = $this->argument("host");
$target = $this->option("target");
        if (!$target)
{
$target = "../distribution";
}
        $url  = Config::get("host." . $host . ".url");
$path = Config::get("host." . $host . ".path");
        $command = "rsync --verbose --progress --stats --compress --recursive --times --perms -e ssh " . $target . "/ " . $url . ":" . $path . "/";
        $escaped = escapeshellcmd($command);
        $this->line(trim("
<info>Synchronizing distribution files to</info>
<comment>" . $host . " (" . $url . ")</comment>
<info>.</info
"));
        exec($escaped, $output);
        foreach ($output as $line)
{
if (starts_with($line, "Number of files transferred"))
{
$parts = explode(":", $line);

$this->line(trim("
<comment>" . trim($parts[1]) . "</comment>
<info>files transferred.</info>
"));
}
            if (starts_with($line, "Total transferred file size"))
{
$parts = explode(":", $line);
                $this->line(trim("
<comment>" . trim($parts[1]) . "</comment>
<info>transferred.</info>
"));
}
}
}
    protected function getArguments()
{
return [
[
"host",
InputArgument::REQUIRED,
"Destination host."
]
];
}
    protected function getOptions()
{
return [
[
"target",
null,
InputOption::VALUE_OPTIONAL,
"Distribution path.",
null
]
];
}
}
This file should be saved as app/commands/DistributeCommand.php.

The DistributeCommand class accepts a host (remote server name) argument and a --target option. Like the copy and clean commands; the --target option will override the default ../distribute folder with one of your choosing.

The host argument needs to match a key in your app/config/host.php configuration file. It carefully constructs and escapes a shell command instruction rsync to synchronise files from the distribution folder to a path on the remote server.

Once the files have been synchronised, it will inspect the messy output of the rsync command and return number number of bytes and files transferred.

The intricacies of SSH and Rsync are outside the scope of this tutorial. You can learn more about Rsync at: https://calomel.org/rsync_tips.html
You can watch the progress of an upload (to the remote server) by connecting via SSH, navigating to the folder and running the command: du -hs

A Note On Portability

Portability refers to how easily code will run on any environment. Most of the commands created in this tutorial are portable. The parts that aren’t too portable are those relating to Rsync. Rsync is a *nix utility, and is therefore not found on Windows machines.

If you find the deploy command gives you headaches; feel free to jump in just before it and deploy the distribution folder (after build, copy and clean commands) by whatever means works for you.

A Note On Preprocessors

Preprocessors are things which convert some intermediate languages into common languages (such as converting Less, SASS, Stylus into CSS). These are often combined with deployment workflows.

Due to time constraints; I’ve not covered them in this tutorial. If you need to add them then a good place would be as a filter in the asset:combine or asset:minify commands. You may also want to add another command (to be executed before those two) which preprocesses any of these languages.

A Note On Images

Image optimisation is a huge topic. I might go into detail on how to optimise your images (as part of the deployment process) in a future tutorial. Assetic does provide filters for this sort of thing; so check its documentation if you feel up to the challenge!

Conclusion

Laravel 4 is packed with excellent tools to enable secure deployment. In addition, it also has an excellent ORM, template language, input validator and filter system. And that’s just the tip of the iceberg!

If you found this tutorial helpful, please tell me about it @followchrisp and be sure to recommend it to PHP developers looking to Laravel 4!


This tutorial comes from a book I’m writing. If you like it and want to support future tutorials; please consider buying it. Half of all sales go to Laravel.