페이지

2018년 2월 11일 일요일

Chapter 2. Setting up a Laravel Development Environment

- Composer
Composer is a dependency manager for PHP, much like NPM for Node or RubyGems for Ruby. You'll need Composer to install Laravel, update Laravel, and bring in external dependencies.

- Local Development Environments

However, Laravel offers two tools for local development, Valet and Homestead, and  we'll cover both briefly. If you're unsure of which to use, I'd recommend useing Valet and just skimming the Homested section; however, both tools are valuable and worth understanding.

- Laravel Valet
If you want to use PHP's build-in web server, your simplest option in to serve every site from a localhost URL. If your urn php -S localhost:8000 -t kpublic from yhour Laravel site's root folder, PHP's built-in web server your site a http://localhost:8000/. You can also run php artisan serve once you have your application setup to easily spin up an equivalent server

But if yhou're interrested in tying each of your sites to a specific development domain, you'll need to get comfortabel with your operationg system's host file and use a tool like dnsmasq. Let's instead tyr something simpler.

If your're a Mac user (there are also unofficial forks for Windows and Linux), Laravel Valet takes away the need to connnect  yhour domains to your applicaiton folders. Valet install dnsmasq and a series of PHP scripts that make it possible to tyhpe laravel new myapp && open myapp.dev and for it to just work. You'll need to install a few tools using Homebrew, which thedocumentaion will walk you through, but the steps from initial installation to serving your apps are few and simple.

Imstall Valet (see the docs for the latest installation instruction- it's under very active developoment at this time of writing), and point it at one or more directories whrere your sites will live. I ran valet park from my ~/Sites directory, which is where I put all of my under-development apps. Now, you can just add .dev to the end of the directory name and visit it in your browser.

Valet makes it easy to serve all folders in a given folder a "FOLDERNAME.dev" using valet park, to server just a single folder using valet link, to open the Valetserved domain for qa folder using valet open, to serve the Valet site with HTTPS using valet secure, and to open an ngrok tunnel so you can share your site with others with valet share.

- Laravel Homestead
Homestead is another tool you might want to use to set up your local developement environment. It't configuration tool that site on top of Vagrant and providers a preconfigured virtual machine image that i perfectly set up for Laravel developemnt, and mirrors the most common production environment that many Laravel sites run on.

Setting up Homestead

If your choose to use Homestead, it's going to take a bit more work to set up than something like MAMP or Valet. The benefits are myriad, however: configured correctly,  your local environment can be incredibly close to your ermote working environmnent; you won't have to worry about updating yuour dependencies on your local machine; and you can learn all about the structure of Ubuntu servers from the safety of your local machine.

What tools do Homestread Offer?
Your can always upgrad the individual components of your Homestread virtual machine, but here are a few inmportant tools Homestgead comes with by default:
- To run the server and serve the site, Ubuntu, PHP, and Nginx (a web server similar to Apache).
- For database/storage and queues, MySQL, Postgres, Redis, Memcached, and beanstalkd.
- For build steps and other tools, Node.

Installing Homesterad''s dependencies
First, you'll need to deonload and install either VirtualBox or VMWare, VirturalBox is most common because it's free.

Next, download and install Vagrant.

vagrant is convenient because it makes it easy for your to rectre a new local virtual machine from a precreated "box", which is essentially a tmeplate for a virtual machine. So, the next step is to run vagrant box andd laravel/homestread from your terminal to download the box.

Installing Homestead

Next, let's actually install Homeestead. You can install multiple instances of Homestead(perhaps hosting a different Homestread box per project), but I perfer a single Homestread virtual machine for all of my projects. It you wnat on per project, you'll want to installl Homestead in your project directory; check the Homestread documentation online for instructions. If you want a single virtual machine for all of your projects, instlal Homesterad in your user's home directory useing the following command:

git clone https://github.com/laravel/homestead.git ~/Homestead

Now, run the initialization script from wherevent you put the Homestead directory:

bash ~/Homestead/init/sh
This will place Homestead's primary configuration file, Homestead.yaml, in a new ~/.homestead directory.

Configuring Homestead
Open up Homestead.yaml and configure it how yhou'd like. Here's what it looks like out of the box:
ip : "192.168.10.10"
memory: 2048
cpus: 1
oorivuder: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
   - ~/.ssh/id_rsa

folders:
   - map: hoestead.app
      to: /home/vagrant/Code

sites:
   - map: homestead.app
      to:/home/vagrant/Code/Laravel/public

databases:
     - homestead

# blackfire:
#      - id: foo
#        token: bar
#        client-id: foo
#        client-token: bar


# ports:
#         - send: 5000
#           to : 5000
#          - send: 7777
#           to : 7777
#           protocol: udp

You'll need to tell it your provider( likely virtualbox), point it to yhour public SSH key(by default ~/.ssh/id_rsa.pub; if you don't have one, GitHub has a gread tutorial on creating SSH keys), map folders and sites to their local machine equivalents, and provison a database.

Mapping folers in Homestead allows you to edit files on your local machine and have those files show up in your Vagrant box so they cna be serverd. For example, it you rhave a ~/Sites directory whrere your put all of your code, your'd map the folders in Homeestead by replacing the folders section in Homestead.yaml with the floowing:

folders:
   - map: ~/Sites
       to: /home/vagrant/Sites

You've now just created a directory in your Homestead virtual machine at /home/vagrant/Sites that will mirror your computer's directory at ~/Sites.

Top-level domains for development sites
You cna chooese nay converntion for local development sites' URLs, but .app and .dev are the most common. Homesteread suggest. .app, so if I'm working on a local copy of symposiumapp.com, I'll develop at symposiumapp.app.
Technically, .app and .dev are valid TLDs, so by choosing them for your won internal use, you could be confliciting with real domains.
This doesn't really bother me, but if you're concerned, there are four TLDs reserved for development purposes: .example, .test, .invlid, and .localhost.

Now, let's setup our first example website. Let's say our live site is going to be projectName.com. In Homestead,yaml, we'll map our local development folder to projectName.app, so we have a separate URL to visit for local development:


sites:
       -map: projectName.app
         to: /home/vagrant/Sites/projectName/public

As you can see, we're mapping the URL projectName.app to the virtual machine directory /home/vagrant/Sites/projectName/public, which is the public folder within our Laravel install. We'll learn more about that later.

Finlly, you're going to need to teach your local machine that, when you try to visit proejctName.app, it should look at your computer's local IP address to resolve it Mac and Linux users should edit /etc/hosts, and Windows users C:\Windows\System32\direvers\etc]host. Add a line to this file that looks lick this:

192. 186.10.10 projectName.app

Once you've provisioned Homeestead, your site will be available to browse (on your machine) at http:.//projectName.app/.

Creating databases in Homestead
Just like you can define a site in Homestead.yaml, you can slso define a database. Databases are a lot simpler, because  you're only telling the provisioner to create a database with that name, nothing else. We dothis a follows:

databases:
     -projectname

Provisioning Homestead
The first time your acually turn on a Homestead box, you need to tell Vagrant to initialize it. Navigate to your Homestead directory and run vagrant up:

cd ~/Homestead
bagrant up

Your Homestead box is now up and running: it's mirroring a local folder, and it's serving it to a URL you can visit in any browser on your computer. It also has created a MySQL database. Now that your have that environment running, you're ready to test up your first Laravel project - but first, a quick note about using Homestead day-to-day.

Using Homestead day-to-day

It's common to leave your Homestead virtual machine up and running at all times, but if you don't, or if you have recently restarted your computer, you'll need to know how to spin the box up and down.

Since Homestead is based on Vagrant commands, you'll ust use basic Vagrant commands for most Homestead actions. Change to the directory where you installed Homestead (using cd) and then run the following commands as needed:

- vagrant up spins up the Homestead box.
- vagrant suspend takes a snapshot of where the box is and tehn shuts it down;
like "hibernating" a desktop machine.
- vagrant halt shuts the entire box down; like turning off a desktop machine.
- vagrant destory deletes the entire box; like formatting a desktop machine.
- vagrant provision re-runs the provisioners on the preexisting box.

Connecting to Homestead databses from desktop applications
If yhou use a dsktop application like Sequel Pro, you'll likely want to connect to your Homestead MySQL databases from your host machine. These settings will get you going:

- Connection type: Standard(non-SSH)
- Host: 127.0.0.1
- Username:homestead
- Password:secret
- Post:33060

Creating a New Laravel Proejct
There are two ways to create a new Laravel proejct, but both are run from the command line. The first option is to globallyinstlal the Laravel installer tool( using Composer); the second is to use Composer's create-project feature.
You can learn about both options in more detail on the Installation documentation page, but I'd recommend the Laravel installer tool.

Installing Laravel with the Laravel Installer Tool
If you have Composer installed globally, installing the Laravel installer tool is as simple as running the following command:

composer global require "laravel/installer=~1.1"
Once you have the Laravel installer tool installed, spinning up a new Laravel proejct is simple. Just run this command from yhour command line:

laravel new proejctName

This will create a new subdirectory of your current directory named projectName and install a bare Laravel project in it.

Installing Laravel with Composer's create-proejct feature
Composer also offers a feature called create-proejct for creating new projects with a particular skeleton.to use this tool to create a new Laravel project, issue the following command:

composer create-proejct laravel/laravel projectName --prefer -dist

Just liek the installer tool, this will crfeate a subdirectory of your current directory named proejctName that contains a skeleton Laravel install. ready for you to develop.

Laravel's Directory Structure
When you openup a direcotry that contains a skeleton Laravel application, you'll see the following files and direcories:

app/
bootstrap/
config/
database/
public/
resources/
routes/
storage/
tests/
vendor/
.env
.ev.example.
.gitattributs/
.gitignore
artisan
composer.json
compoer.lock
gulpfile.js
package.sjon
phpunit.xml
readme.md
server.php

Let's walk through them one by one to get familiar.

The Folders
The root directory contains the follwoing folders by default:
- app is where the bulk of your actual application will go. Models, controllers, route definitions, commands, and yhour PHP domain code all go in here.
- bootstrap contains the files that the Laravel framework uses to boot every time it runs.
- config is whrere all the configuration files live.
- database is where database migrations and seeds live.
- public is the directory the server points to when it's serving the website. This contains index.php, whichis the front controller that kicks off the bootstrapping process and routes all requests appropriately. It's also where any public-facing files like images, stylesheets, scripts, or downloads go.
- reousrce is when non-PHP files that are needed for other scripts live. Views, language files, and (opotionally)Sass/LESS and source JavaScript files live here.
- routes is where all of the route definitions live, both for HTTP routes and "console routes," or Artisan commands.
- storage is where cashes, logs, and compiled system files live.
- tests is where unit and integration tests live.
- vendor is where Composer installs its dependencies. It's Git-ignored(marked to be excluded from your version control system), as Composer is expected to run as a part of your deploy process on any remote servers.

The Loose Files
The root directory also contains the following files:

- .env and .env.example are the files that dictate the environment variables (variables that are expected to be different in each environmnet and are therefore not committed to version control). .env.example is a template that each environment should duplicate to create its own .env file, which is Git-ignored.

-artisan is the file that allows you to run Artisan commands (see Chapter 7) from the command line.
-.gitignore and .gitattributes are Git configuration files.
- composer.json and composer.lock are the configuration files for Composer; composer.json is user-editable and composer.lock is not. These files share some basic information about this proejct and aslo define its PHP dependencies.
-gulpfile.js is the (optional) configuration file for Elixir and Gulp. This is for compiling and processing your frontend assets.
-package.json is like composer.json but for frontend asserts.
-phpuniut.xml is a configuration file for PHPUnit, the tool Laravel users for testing out of the box.
- readme.md is a Markdown file giving a basic introduction to Laravel.
-server.php is a backup server that tries to allow less-capable servers to still perview the Laravel application.

Configuration
The core settings of your Laravel application-database connection, queue and mail settings, etc. - live in files in the config folder. Each of these files returns an array, and each value in the array will be accessible by a config key that is comprised of the filename and all descendant keys, separated by dots(.)

So, if you create a file at config/service.php that looks like this:

// config/services.php
return [
       'sparkost' => [
            'secret' => 'abcdefg'
      ]
 ];

you will now have access to that config variable using config('services.spark post.secret').
Any configuration variables that should b distinct for each environment(and therefore not committed to source control) will instead live in your .env files. Let's say your want to use a different Bugsnag API key for each environment. You'd set the config file to pull it from .env:

  // config/services.php
  return [
       'bugsnag' => [
              'api_key'   => env('BUGSANG_API_KEY')
       ]
 ];

This env() helper function pulls a value from your .env file with tat same key. So now, add that key to your .env (settings for this environment)and .env.example(template for all environmnets) files:
 BUGSNAG_API_KEY=oinfp9813410942
your .env file already contains quite a few environment-specific variables needed by the framework, like which mail driver you'll be suing and what your basic database settings are.

Up and Running

You're now up and running with a bare Laravel install, Run git init, commit the bare files with git add . and git commit, and you're ready to start coding. That's it!
And if you're using Valet, you can run the follwing commands and instantly see your site live in your browser:
laravel new myProejct && cd myProejct && valet open

Every time I start a new project, these are the steops I take:

laravel new  myProejct
cd myProejct
git init
git add .
git commit -m "Inital commit"

I keep all of my sites in a ~/Sites folder, which I hava set up as my primary Valet directory, so in this case I'd instantly have myProejct.dev accessible in mybrowser with no added work. I can edit .evn and point it to particular database, add that database in my MySQL app, and I'm ready to start coding.

Lambo
I perform this set of steps so often that I created a simple global Composer package to do it for me. It's called Lambo, and you can learn more about it on GitHub.

Testing
In every chapter after this, the "Testing" section at tne end of the chapter will show you how to wirte test for the feature of reatures that were coverd. Since this chater doesn't cover a testable feature, let's talk test quickly.(To lean more about wirting and running tests in Laravel, head over to Chapter 12.)


Out of the box, Laravel bring in PHPUnit as dependency and is configured to ren the tests in any file in the tests directory whose name ends with Test.php(for example, tests/UserTest.php).

So, the simplest way to write tests is to create a file in the tests directory with a anme that ends with Test.php. And the easiest way to run them is to run ./vendor/bin/phpunit from the command line (in the proejct root).

If nay tests require database access, be user to run your tests form the machine where your database is hosted- so if you're hosting your databases in Vagrant, make sure to ssh into your Vagrant box to run your test from there. Again, your can learn about this and much more in Chapter 12.


TL;DR
Since Laravel is a PHP framework, it's very simple to serve it locally. Laravel also provides two tools for maanging your local developoment: a simpler tool called Valet that uyses your local machine to provide your dependencies, and a preconfigured Vagrant setup named Homested. Laravel relies on, and can be installed by, Composer, and comes out of the box with a series of folders and files that rreflect both its conventiions and its relationship with other open source tools.








댓글 없음: