In this chapter, we will cover:
Installing Laravel as a git submodule
Setting up a virtual host and development environment in Apache
Creating "clean" URLs
Configuring Laravel
Using Laravel with Sublime Text 2
Setting up your IDE to autocomplete Laravel's namespaces
Using Autoloader to map a class name to its file
Creating advanced Autoloaders with namespaces and directories
In this chapter, we'll learn how to get Laravel up-and-running with ease and make sure it's simple to update when any core changes are made. We'll also get our development and coding environment set up to be very efficient so we can focus on writing great code and not have to worry about issues not related to our applications. Finally, we'll look at some ways to get Laravel to automatically do some work for us so we'll be able to extend our application in very little time.
There may be a time when we want to have our Laravel installation separate from the rest of our public files. In this case, installing Laravel as a git submodule would be a solution. This will allow us to update our Laravel files through git without touching our application code.
To get started, we should have our development server running as well as have git installed. In the server's web directory, create a myapp
directory to hold our files. Installation will all be done in the command line.
To complete this recipe, follow these steps:
In your terminal or command line, navigate to the root of
myapp
. The first step is to initialize git and download our project files:$ git init $ git clone git@github.com:laravel/laravel.git
Since all we need is the
public
directory, move to/laravel
and delete everything else:$ cd laravel $ rm –r app bootstrap vendor
Then, move back to the root directory, create a
framework
directory, and add Laravel as a submodule:$ cd .. $ mkdir framework $ cd framework $ git init $ git submodule add https://github.com/laravel/laravel.git
Now we need to run Composer to install the framework:
php composer.phar install
Tip
More information about installing Composer can be found at http://getcomposer.org/doc/00-intro.md. The rest of the book will assume we're using
composer.phar
, but we could also add it globally and simply call it by typingcomposer
.Now, open
/laravel/public/index.php
and find the following lines:require __DIR__.'/../bootstrap/autoload.php'; $app = require_once __DIR__.'/../bootstrap/start.php';
Change the preceding lines to:
require __DIR__.'/../../framework/laravel/bootstrap/autoload.php'; $app = require_once __DIR__.'/../../framework/laravel/bootstrap/start.php';
For many, simply running git clone
would be enough to get their project going. However, since we want to have our framework act as a submodule, we need to separate those files from our project.
First, we download the files from GitHub, and since we don't need any of the framework files, we can delete everything but our public folder. Then, we create our submodule in the framework
directory and download everything there. When that's complete, we run composer install
to get all our vendor packages installed.
To get the framework connected to our application, we modify /laravel/public/index.php
and change the require
paths to our framework directory. That will let our application know exactly where the framework files are located.
When developing our Laravel app, we'll need a web server to run everything. In PHP 5.4 and up, we can use the built-in web server, but if we need some more functionality, we'll need a full web stack. In this recipe, we'll be using an Apache server on Windows, but any OS with Apache will be similar.
This recipe requires a recent version of WAMP server, available at http://wampserver.com, though the basic principle applies to any Apache configuration on Windows.
To complete this recipe, follow these steps:
Open the WAMP Apache
httpd.conf
file. It is often located inC:/wamp/bin/apache/Apach2.#.#/conf
.Locate the line
#Include conf/extra/httpd-vhosts.conf
and remove the first#
.Move to the
extra
directory, open thehttpd-vhosts.conf
file, and add the following code:<VirtualHost *:80> ServerAdmin {your@email.com} DocumentRoot "C:/path/to/myapp/public" ServerName myapp.dev <Directory "C:/path/to/myapp/public"> Options Indexes FollowSymLinks AllowOverride all # onlineoffline tag - don't remove Order Deny,Allow Deny from all Allow from 127.0.0.1 </Directory> </VirtualHost>
Restart the Apache service.
Open the Windows hosts file, often in
C:/Windows/System32/drivers/etc
, and open the filehosts
in a text editor.At the bottom of the file, add the line
127.0.0.1 myapp.dev
.
First, in the Apache config file httpd.conf
, we uncomment the line to allow the file to include the vhosts
configuration files. You can include the code directly in the httpd.conf
file, but this method keeps things more organized.
In the httpd-vhosts.conf
file, we add our VirtualHost code. DocumentRoot
tells the server where the files are located and ServerName
is the base URL that the server will look for. Since we only want to use this for our local development, we make sure to only allow access to the localhost with the IP 127.0.0.1
.
In the hosts
file, we need to tell Windows which IP to use for the myapp.dev
URL. After restarting Apache and our browser, we should be able to go to http://myapp.dev
and view our application.
While this recipe is specific to Windows and WAMP, the same idea can be applied to most Apache installations. The only difference will be the location of the httpd.conf
file (in Linux Ubuntu, it's in /etc/apache2
) and the path to the public
directory for DocumentRoot (in Ubuntu, it might be something like /var/www/myapp/public
). The hosts
file for Linux and Mac OS X will be located in /etc/hosts
.
When installing Laravel, the default URL we will use is http://{your-server}/public
. If we decide to remove /public
, we can use Apache's mod_rewrite
to change the URL.
For this recipe, we just need a fresh installation of Laravel and everything running on a properly configured Apache server.
To complete this recipe, follow these steps:
In our app's root directory, add a
.htaccess
file and use this code:<IfModule mod_rewrite.c> RewriteEngine On RewriteRule ^(.*)$ public/$1 [L] </IfModule>
Go to
http://{your-server}
and view your application.
After installing Laravel, it's pretty much ready to go without much need for configuration. However, there are a few settings we want to make sure to update.
To complete this recipe, follow these steps:
Open
/app/config/app.php
and update these lines:'url' => 'http://localhost/, 'locale' => 'en', 'key' => 'Seriously-ChooseANewKey',
Open
app/config/database.php
and choose your preferred database:'default' => 'mysql', 'connections' => array( 'mysql' => array( 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'database', 'username' => 'root', 'password' => '', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ), ),
In the command line, go to the root of the app and make sure the
storage
folder is writable:chmod –R 777 app/storage
Most of the configuration will happen in the /app/config/app.php
file. While setting the URL isn't required, and Laravel does a great job figuring it out without setting it, it's always good to remove any work from the framework that we can. Next, we set our location. If we choose to provide localization
in our app, this setting will be our default. Then, we set our application key, since it's best to not keep the default.
Next, we set which database driver we'll be using. Laravel comes with four drivers out of the box: mysql, sqlite, sqlsrv (MS SQL Server), and pgsql (Postgres).
Finally, our app/storage
directory will be used for keeping any temporary data, such as sessions or cache, if we choose. To allow this, we need to make sure the app can write to the directory.
For an easy way to create a secure application key, remove the default key and leave it empty. Then, in your command line, navigate to your application root directory and type:
php artisan key:generate
That will create a unique and secure key and automatically save it in your configuration file.
One of the most popular text editors used for coding is Sublime Text. Sublime has many features that make coding fun, and with plugins, we can add in Laravel-specific features to help with our app.
Sublime Text 2 is a popular code editor that is very extensible and makes writing code effortless. An evaluation version can be downloaded from http://www.sublimetext.com/2.
We also need to have the Package Control package installed and enabled in Sublime, and that can be found at http://wbond.net/sublime_packages/package_control/installation.
The Laravel snippets in Sublime Text 2 greatly simplify writing common code, and it includes pretty much everything we'll need for application development. For example, when creating a route, simply start typing Route
and a list will pop up allowing us to choose which route we want, which then automatically completes the rest of the code we need.
Most IDEs (Integrated Development Environment) have some form of code completion as part of the program. To get Laravel's namespaces to autocomplete, we may need to help it recognize what the namespaces are.
For this recipe, we'll be adding namespaces to the NetBeans IDE, but the process will be similar with others.
Follow these steps to complete this recipe:
Download the following pre-made file that lists the Laravel namespaces: https://gist.github.com/barryvdh/5227822.
Create a folder anywhere on your computer to hold this file. For our purposes, we'll add the file to
C:/ide_helper/ide_helper.php
:After creating a project with the Laravel framework, navigate to File | Project Properties | PHP Include Path:
Click on Add Folder… and then add the folder at
C:/ide_helper
.Now when we start typing the code, the IDE will automatically suggest code to complete:
Some IDEs need help understanding the syntax of a framework. To get NetBeans to understand, we download a list of all the Laravel classes and options. Then, when we add it to the Include Path, NetBeans will automatically check the file and show us the autocomplete options.
We can have the documents downloaded and updated automatically using Composer. For installation instructions, visit https://github.com/barryvdh/laravel-ide-helper.
Using Laravel's ClassLoader, we can easily include any of our custom class libraries in our code and have them readily available.
To complete this recipe, follow these steps:
In the Laravel
/app
directory, create a new directory namedcustom
, which will hold our custom classes.In the
custom
directory, create a file namedMyShapes.php
and add this simple code:<?php class MyShapes { public function octagon() { return 'I am an octagon'; } }
In the
/app/start
directory, openglobal.php
and updateClassLoader
so it looks like this:ClassLoader::addDirectories(array( app_path().'/commands', app_path().'/controllers', app_path().'/models', app_path().'/database/seeds', app_path().'/custom', ));
Now we can use that class in any part of our application. For example, if we create a route:
Route::get('shape', function() { $shape = new MyShapes; return $shape->octagon(); });
Most of the time, we will use Composer to add packages and libraries to our app. However, there may be libraries that aren't available through Composer or custom libraries that we want to keep separate. To accomplish this, we need to dedicate a spot to hold our class libraries; in this case, we create a directory named custom
and put it in our app
directory.
Then we add our class files, making sure the class names and filenames are the same. This could either be classes we create ourselves or maybe even a legacy class that we need to use.
Finally, we add the directory to Laravel's ClassLoader. When that's complete, we'll be able to use those classes anywhere in our application.
If we want to be sure that our custom classes don't conflict with any other class in our app, we will need to add them to a namespace. Using the PSR-0 standard and Composer, we can easily autoload these classes into Laravel.
To complete this recipe, follow these steps:
Inside the
/app
directory, create a new directory namedcustom
, and inside ofcustom
, create a directory namedCustom
, and inCustom
, create a directory namedShapes
.Inside the
/app/custom/Custom/Shapes
directory, create a file namedMyShapes.php
and add this code:<?php namespace Custom\Shapes; class MyShapes { public function triangle() { return 'I am a triangle'; } }
In the root of the application, open the
composer.json
file and locate theautoload
section. Update it so it looks like this:"autoload": { "classmap": [ "app/commands", "app/controllers", "app/models", "app/database/migrations", "app/database/seeds", "app/tests/TestCase.php", ], "psr-0": { "Custom": "app/custom" } }
Open the command line and run
dump-autoload
on Composer:php composer.phar dump-autoload
Now we can call that class by using its namespace. For example, if we create a route:
Route::get('shape', function() { $shape = new Custom\Shapes\MyShapes; return $shape->triangle(); });
Namespaces are a powerful addition to PHP, and they allow our classes to be used without us having to worry about their class names interfering with other class names. By autoloading namespaces in Laravel, we could create a complex group of classes and never have to worry about class names conflicting with other namespaces.
For our purposes, we're loading the custom class through composer, and the PSR-0 standard of autoloading.
To further extend the use of our namespaced class, we could use the IoC to bind it to our app. More information can be found in the Laravel documentation at http://laravel.com/docs/ioc.