Mike Korcha

Blog

The stuff in this article was brought from my old site. It may be woefully out of date.

Using Composer Packages in a Laravel Application

As of version 4, the Laravel framework can be installed entirely from the Composer dependency manager. A major advantage of this is that you can choose to use only certain parts of the framework by installing those particular components within your own application. What seems to go unseen (at least in my experience) is that other Composer packages can be installed for use within your Laravel application, with less hassle than you might think.

Assumptions

  • Latest version of Composer
  • Running Laravel 4 with a Composer file

Composer

The first thing we want to do is edit our composer.json file to include the library we want as a requirement. For this example, I'll be using Michel Fortin's PHP Markdown package (which happens to be the one used with this blog). In composer.json, we want to edit our requirements to look similar to this:

"require": {
    "laravel/framework": "4.0.*",
    "michelf/php-markdown": "1.4.*@dev"
},

Next, we just have to install via Composer:

php composer.phar install

Application

Since Composer generates an autoload file that Laravel already loads, we have access to "MichelfMarkdown" immediately after install. However, we'd have to call it from there each time, unless we set up the alias.

In your Laravel app/config/app.php file, go down to the "aliases" array, and add the name into the array:

'Validator'       => 'Illuminate\Support\Facades\Validator',
'View'            => 'Illuminate\Support\Facades\View',
// Other Composer packages
'Markdown'        => 'Michelf\Markdown',

Now, anywhere you want to use the package, you can just call it in your code. For example, with the Markdown package, I want to show a message in a view, which is written in Markdown:

View::make('message', array(
    'title'         => $message->title,
    'from'          => $message->from,
    'to'            => $message->to,
    'content'       => Markdown::defaultTransform($message->content),
));

By utilizing Composer packages along with Laravel, you can get rid of a ton of extra effort that would be spent reinventing the wheel, and instead spend more time focusing on creating a better application. There are tons of packages available on Packagist, so give it a shot!


  • php5
  • laravel
Written 2014-03-07