陈斌彬的技术博客

Stay foolish,stay hungry

Getting Started With PHP on Heroku

img

Getting Started with PHP on Heroku

Set up

In this step you will install the Heroku Toolbelt. This provides you access to the Heroku Command Line utility, as well as git and Foreman, tools you’ll use in later steps.

Once installed, you can use the heroku command from your command shell.

Log in using the email address and password you used when creating your Heroku account:

➜ /Users/apple git:(master) ✗> heroku login
Enter your Heroku credentials.
Email: 845040571@qq.com
Password (typing will be hidden):
Authentication successful.
updating Heroku CLI...done. Updated to 3.37.7

Authenticating is required to allow both the heroku and git commands to operate.

Note that if you’re behind a firewall that requires use of a proxy to connect with external HTTP/HTTPS services, you can set the HTTP_PROXY or HTTPS_PROXY environment variables in your local development environment before running the heroku command.

Prepare the app

In this step, you will prepare a simple application that can be deployed.

Execute the following commands to clone the sample application:

$ git clone https://github.com/heroku/php-getting-started.git
$ cd php-getting-started

You now have a functioning git repository that contains a simple application as well as a composer.json file. Make sure you’ve installed Composer. Heroku uses Composer for dependency management in PHP projects, and the composer.json file indicates to Heroku that your application is written in PHP.

img

Here is install composer:

img

在项目列表中,会有一个 composer.phar 文件,里面包含了所有逻辑代码行工具。你可以通过运行下面代码来确定是否安装成功。 img

➜ /Users/apple git:(master) ✗> sudo mv composer.phar /usr/bin/composer

把这个文件移到 bin 目录下,它允许你简化命令

➜ /Users/apple git:(master) ✗> composer about
Composer - Package Management for PHP
Composer is a dependency manager tracking local dependencies of your projects and libraries.
See https://getcomposer.org/ for more information.

Deploy the app

In this step you will deploy the app to Heroku.

Create an app on Heroku, which prepares Heroku to receive your source code:

img

When you create an app, a git remote (called heroku) is also created and associated with your local git repository.

Heroku generates a random name (in this case sharp-rain-871) for your app, or you can pass a parameter to specify your own app name.

Now deploy your code:

➜ /Users/apple/php-getting-started git:(master)> git push heroku master
Counting objects: 103, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (51/51), done.
Writing objects: 100% (103/103), 17.37 KiB | 0 bytes/s, done.
Total 103 (delta 39), reused 103 (delta 39)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> PHP app detected
remote: -----> No runtime required in composer.json, defaulting to PHP 5.6.10.
remote: -----> Installing system packages...
remote:        - PHP 5.6.10
remote:        - Apache 2.4.10
remote:        - Nginx 1.6.0
remote: -----> Installing PHP extensions...
remote:        - zend-opcache (automatic; bundled)
remote: -----> Installing dependencies...
remote:        Composer version 1.0.0-alpha10 2015-04-14 21:18:51
remote:        Loading composer repositories with package information
remote:        Installing dependencies from lock file
remote:          - Installing psr/log (1.0.0)
remote:            Downloading: 100%
remote:
remote:          - Installing monolog/monolog (1.11.0)
remote:            Downloading: 100%
remote:
remote:          - Installing symfony/routing (v2.5.5)
remote:            Downloading: 100%
remote:
remote:          - Installing symfony/http-foundation (v2.5.5)
remote:            Downloading: 100%
remote:
remote:          - Installing symfony/event-dispatcher (v2.5.5)
remote:            Downloading: 100%
remote:
remote:          - Installing symfony/debug (v2.5.5)
remote:            Downloading: 100%
remote:
remote:          - Installing symfony/http-kernel (v2.5.5)
remote:            Downloading: 100%
remote:
remote:          - Installing pimple/pimple (v1.1.1)
remote:            Downloading: 100%
remote:
remote:          - Installing silex/silex (v1.2.2)
remote:            Downloading: 100%
remote:
remote:        Generating optimized autoload files
remote: -----> Preparing runtime environment...
remote: -----> Discovering process types
remote:        Procfile declares types -> web
remote:
remote: -----> Compressing... done, 73.1MB
remote: -----> Launching... done, v3
remote:        https://hidden-reef-2185.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/hidden-reef-2185.git
 * [new branch]      master -> master

The application is now deployed. Ensure that at least one instance of the app is running:

➜ /Users/apple/php-getting-started git:(master)> heroku ps:scale web=1
Scaling dynos... done, now running web at 1:1X.

Now visit the app at the URL generated by its app name. As a handy shortcut, you can open the website as follows:

➜ /Users/apple/php-getting-started git:(master)> heroku open
Opening hidden-reef-2185... done

View logs

Heroku treats logs as streams of time-ordered events aggregated from the output streams of all your app and Heroku components, providing a single channel for all of the events.

View information about your running app using one of the logging commands, heroku logs:

➜ /Users/apple/php-getting-started git:(master)> heroku logs --tail
2015-06-13T05:59:55.009940+00:00 heroku[api]: Enable Logplex by 845040571@qq.com
2015-06-13T05:59:55.009940+00:00 heroku[api]: Release v2 created by 845040571@qq.com
2015-06-13T06:03:19.439916+00:00 heroku[api]: Scale to web=1 by 845040571@qq.com
2015-06-13T06:03:19.480753+00:00 heroku[api]: Deploy 03b1ebf by 845040571@qq.com
2015-06-13T06:03:19.480753+00:00 heroku[api]: Release v3 created by 845040571@qq.com

Press Control+C to stop streaming the logs.

Define a Procfile

Use a Procfile, a text file in the root directory of your application, to explicitly declare what command should be executed to start your app.

The Procfile in the example app you deployed looks like this:

web: vendor/bin/heroku-php-apache2 web/

This declares a single process type, web, and the command needed to run it. The name web: is important here. It declares that this process type will be attached to the HTTP routing stack of Heroku, and receive web traffic when deployed.

Procfiles can contain additional process types. For example, you might declare one for a background worker process that processes items off of a queue.

Scale the app

Right now, your app is running on a single web dyno. Think of a dyno as a lightweight container that runs the command specified in the Procfile.

You can check how many dynos are running using the ps command:

➜ /Users/apple/php-getting-started git:(master)> heroku ps
=== web (1X): `vendor/bin/heroku-php-apache2 web/`
web.1: up 2015/06/13 14:03:32 (~ 13m ago)

Having only a single web dyno running will result in the dyno going to sleep after one hour of inactivity. This causes a delay of a few seconds for the first request upon waking. Subsequent requests will perform normally.

To avoid this, you can scale to more than one web dyno. For example:

➜ /Users/apple/php-getting-started git:(master)> heroku ps:scale web=2

For abuse prevention, scaling the application may require account verification. If your account has not been verified, you will be directed to visit the verification site.

For each application, Heroku provides 750 free dyno-hours. Running your app at 2 dynos would exceed this free, monthly allowance, so scale back:

➜ /Users/apple/php-getting-started git:(master)> heroku ps:scale web=1
Scaling dynos... done, now running web at 1:1X.

Declare app dependencie

Heroku recognizes an app as PHP by the existence of a composer.json file in the root directory.

The demo app you deployed already has a composer.json, and it looks something like this:

1
2
3
4
5
6
7
8
9
{
  "require" : {
    "silex/silex": "~1.1",
    "monolog/monolog": "~1.7"
  },
  "require-dev": {
    "heroku/heroku-buildpack-php": "*"
  }
}

The composer.json file specifies the dependencies that should be installed with your application. When an app is deployed, Heroku reads this file and installs the appropriate dependencies into the vendor directory.

Your PHP app can then make use of the dependencies after a simple require:

require('../vendor/autoload.php');

Run the following command to install the dependencies, preparing your system for running the app locally:

➜ /Users/apple git:(master) ✗> composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing psr/log (1.0.0)
    Loading from cache
...
Writing lock file
Generating autoload files

You should always check composer.json and composer.lock into your git repo. The vendor directory should be included in your .gitignore file.

Push local changes

In this step you’ll learn how to propagate a local change to the application through to Heroku. As an example, you’ll modify the application to add an additional dependency (the Twig template engine) and the code to use it.

Modify composer.json to include a dependency for twig:

1
2
3
4
5
  "require" : {
    "silex/silex": "~1.1",
    "monolog/monolog": "~1.7",
    "twig/twig": "~1.0"
  }

As you’ve introduced a new dependency, ensure it’s fetched:

 ➜ /Users/apple/php-getting-started git:(master) ✗> composer update

Modify index.php so that it uses Twig to render a template. Do this by first adding some code to register a Twig service provider:

1
2
3
4
 // Register the Twig templating engine
$app->register(new Silex\Provider\TwigServiceProvider(), array(
  'twig.path' => __DIR__.'/../views',
));

Then introduce a new route:

1
2
3
4
5
$app->get('/twig/{name}', function ($name) use ($app) {
    return $app['twig']->render('index.twig', array(
        'name' => $name,
    ));
});

When that route is visited, it will pass the name to the Twig renderer, together with the index.twig template.

Now create a views subdirectory to store the templates:

➜ /Users/apple/php-getting-started git:(master) ✗> mkdir views
➜ /Users/apple/php-getting-started git:(master) ✗> cd views

If you get lost making these changes, take a look at the step-2 branch of the sample app.

Now deploy. Almost every deploy to Heroku follows this same pattern.

First, add the modified files to the local git repository. Start by changing back to the root directory of your app, and adding the new files to your local git repository:

➜ /Users/apple/php-getting-started git:(master) ✗> git add .

Now commit the changes to the repository:

➜ /Users/apple/php-getting-started git:(master) ✗> git commit -m "Demo"

Now deploy, just as you did previously:

➜ /Users/apple/php-getting-started git:(master)> git push heroku master

Finally, check that everything is working:

➜ /Users/apple/php-getting-started git:(master)> heroku open

Summary

  1. heroku login
  2. git clone https://github.com/heroku/php-getting-started.git
  3. cd php-getting-started
  4. heroku create
  5. git push heroku master
  6. heroku ps:scale web=1
  7. heroku open
  8. heroku logs –tail
  9. git add .
  10. git commit -m “Demo”
  11. git push heroku master
  12. heroku open

Link