Contextual Binding

Sometimes you may have two classes that utilize the same interface, but you wish to inject different implementations into each class. For example, two controllers may depend on different implementations of the Illuminate\Contracts\Filesystem\Filesystem contract. Laravel provides a simple, fluent interface for defining this behavior:

use Illuminate\Support\Facades\Storage;
use App\Http\Controllers\PhotoController;
use App\Http\Controllers\VideoController;
use Illuminate\Contracts\Filesystem\Filesystem;

$this->app->when(PhotoController::class)
          ->needs(Filesystem::class)
          ->give(function () {
              return Storage::disk('local');
          });

$this->app->when([VideoController::class, UploadController::class])
          ->needs(Filesystem::class)
          ->give(function () {
              return Storage::disk('s3');
          });

Tagging
Occasionally, you may need to resolve all of a certain “category” of binding. For example, perhaps you are building a report aggregator that receives an array of many different Report interface implementations. After registering the Report implementations, you can assign them a tag using the tag method:

$this->app->bind('SpeedReport', function () {
    //
});

$this->app->bind('MemoryReport', function () {
    //
});

$this->app->tag(['SpeedReport', 'MemoryReport'], 'reports');

Once the services have been tagged, you may easily resolve them all via the tagged method:

$this->app->bind('ReportAggregator', function ($app) {
    return new ReportAggregator($app->tagged('reports'));
});

Extending Bindings
The extend method allows the modification of resolved services. For example, when a service is resolved, you may run additional code to decorate or configure the service. The extend method accepts a Closure, which should return the modified service, as its only argument:

$this->app->extend(Service::class, function ($service) {
    return new DecoratedService($service);
});

なに、要するにmiddleware?

Resolving
The make Method
You may use the make method to resolve a class instance out of the container. The make method accepts the name of the class or interface you wish to resolve:

$api = $this->app->make('HelpSpot\API');

Automatic Injection
Alternatively, and importantly, you may “type-hint” the dependency in the constructor of a class that is resolved by the container, including controllers, event listeners, queue jobs, middleware, and more. In practice, this is how most of your objects should be resolved by the container.

For example, you may type-hint a repository defined by your application in a controller’s constructor. The repository will automatically be resolved and injected into the class:

<?php

namespace App\Http\Controllers;

use App\Users\Repository as UserRepository;

class UserController extends Controller
{
    /**
     * The user repository instance.
     */
    protected $users;

    /**
     * Create a new controller instance.
     *
     * @param  UserRepository  $users
     * @return void
     */
    public function __construct(UserRepository $users)
    {
        $this->users = $users;
    }

    /**
     * Show the user with the given ID.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        //
    }
}

Container Events
The service container fires an event each time it resolves an object. You may listen to this event using the resolving method:

$this->app->resolving(function ($object, $app) {
    // Called when container resolves object of any type...
});

$this->app->resolving(HelpSpot\API::class, function ($api, $app) {
    // Called when container resolves objects of type "HelpSpot\API"...
});

なんか、後半よくわかんなくなってきたw

Laravel Service Container

service containerって、dockerのこと!?
The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection. Dependency injection is a fancy phrase that essentially means this: class dependencies are “injected” into the class via the constructor or, in some cases, “setter” methods.

Let’s look at a simple example:

<?php

namespace App\Http\Controllers;

use App\User;
use App\Repositories\UserRepository;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * The user repository implementation.
     *
     * @var UserRepository
     */
    protected $users;

    /**
     * Create a new controller instance.
     *
     * @param  UserRepository  $users
     * @return void
     */
    public function __construct(UserRepository $users)
    {
        $this->users = $users;
    }

    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        $user = $this->users->find($id);

        return view('user.profile', ['user' => $user]);
    }
}

class UserControllerなので、userControllerです。
protected $userなので、変数の$userはこのclass内のみ
$this->usersで$usersを定義
user.profileを表示

In this example, the UserController needs to retrieve users from a data source. So, we will inject a service that is able to retrieve users. In this context, our UserRepository most likely uses Eloquent to retrieve user information from the database. However, since the repository is injected, we are able to easily swap it out with another implementation. We are also able to easily “mock”, or create a dummy implementation of the UserRepository when testing our application.
retrieveは検索
Eloquent 雄弁
コンテナの理解は強力 って言ってる。早くいってよ、それ。

Binding Basics
Almost all of your service container bindings will be registered within service providers, so most of these examples will demonstrate using the container in that context.

Tip!! There is no need to bind classes into the container if they do not depend on any interfaces. The container does not need to be instructed on how to build these objects, since it can automatically resolve these objects using reflection.

Simple Bindings
Within a service provider, you always have access to the container via the $this->app property. We can register a binding using the bind method, passing the class or interface name that we wish to register along with a Closure that returns an instance of the class:

$this->app->bind('HelpSpot\API', function ($app) {
    return new HelpSpot\API($app->make('HttpClient'));
});

Binding A Singleton
The singleton method binds a class or interface into the container that should only be resolved one time. Once a singleton binding is resolved, the same object instance will be returned on subsequent calls into the container:

$this->app->singleton('HelpSpot\API', function ($app) {
    return new HelpSpot\API($app->make('HttpClient'));
});

Binding Instances
You may also bind an existing object instance into the container using the instance method. The given instance will always be returned on subsequent calls into the container:

$api = new HelpSpot\API(new HttpClient);

$this->app->instance('HelpSpot\API', $api);

Binding Primitives
Sometimes you may have a class that receives some injected classes, but also needs an injected primitive value such as an integer. You may easily use contextual binding to inject any value your class may need:

$this->app->when('App\Http\Controllers\UserController')
          ->needs('$variableName')
          ->give($value);

bindingってどれも$this->appだな。

A very powerful feature of the service container is its ability to bind an interface to a given implementation. For example, let’s assume we have an EventPusher interface and a RedisEventPusher implementation. Once we have coded our RedisEventPusher implementation of this interface, we can register it with the service container like so:
なんだ、bindingはよっぽど強力らしい。

$this->app->bind(
    'App\Contracts\EventPusher',
    'App\Services\RedisEventPusher'
);

This statement tells the container that it should inject the RedisEventPusher when a class needs an implementation of EventPusher. Now we can type-hint the EventPusher interface in a constructor, or any other location where dependencies are injected by the service container:

use App\Contracts\EventPusher;

/**
 * Create a new class instance.
 *
 * @param  EventPusher  $pusher
 * @return void
 */
public function __construct(EventPusher $pusher)
{
    $this->pusher = $pusher;
}

つーかなにこれ、laravelのclass覚えんのかよ。

Laravel Request Lifecycle

このへんはコーディングというより設計思想などか?

Introduction
When using any tool in the “real world”, you feel more confident if you understand how that tool works. Application development is no different. When you understand how your development tools function, you feel more comfortable and confident using them.

The goal of this document is to give you a good, high-level overview of how the Laravel framework works. By getting to know the overall framework better, everything feels less “magical” and you will be more confident building your applications. If you don’t understand all of the terms right away, don’t lose heart! Just try to get a basic grasp of what is going on, and your knowledge will grow as you explore other sections of the documentation

Lifecycle Overview
First Things
The entry point for all requests to a Laravel application is the public/index.php file. All requests are directed to this file by your web server (Apache / Nginx) configuration. The index.php file doesn’t contain much code. Rather, it is a starting point for loading the rest of the framework.

The index.php file loads the Composer generated autoloader definition, and then retrieves an instance of the Laravel application from bootstrap/app.php script. The first action taken by Laravel itself is to create an instance of the application / service container
/public/index.phpは公開ファイルです。

HTTP / Console Kernels
Next, the incoming request is sent to either the HTTP kernel or the console kernel, depending on the type of request that is entering the application. These two kernels serve as the central location that all requests flow through. For now, let’s just focus on the HTTP kernel, which is located in app/Http/Kernel.php.
kernel? よく出てくるけど。

middlewareの読み込みclassが記載されてます。

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\TrustProxies::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    ];
}

The HTTP kernel extends the Illuminate\Foundation\Http\Kernel class, which defines an array of bootstrappers that will be run before the request is executed. These bootstrappers configure error handling, configure logging, detect the application environment, and perform other tasks that need to be done before the request is actually handled.

The HTTP kernel also defines a list of HTTP middleware that all requests must pass through before being handled by the application. These middleware handle reading and writing the HTTP session, determining if the application is in maintenance mode, verifying the CSRF token, and more.

The method signature for the HTTP kernel’s handle method is quite simple: receive a Request and return a Response. Think of the Kernel as being a big black box that represents your entire application. Feed it HTTP requests and it will return HTTP responses.
なるほど、

Service Providers
One of the most important Kernel bootstrapping actions is loading the service providers for your application. All of the service providers for the application are configured in the config/app.php configuration file’s providers array. First, the register method will be called on all providers, then, once all providers have been registered, the boot method will be called.

Service providers are responsible for bootstrapping all of the framework’s various components, such as the database, queue, validation, and routing components. Since they bootstrap and configure every feature offered by the framework, service providers are the most important aspect of the entire Laravel bootstrap process

Dispatch Request
Once the application has been bootstrapped and all service providers have been registered, the Request will be handed off to the router for dispatching. The router will dispatch the request to a route or controller, as well as run any route specific middleware.

Focus On Service Providers
Service providers are truly the key to bootstrapping a Laravel application. The application instance is created, the service providers are registered, and the request is handed to the bootstrapped application. It’s really that simple!

Having a firm grasp of how a Laravel application is built and bootstrapped via service providers is very valuable. Of course, your application’s default service providers are stored in the app/Providers directory.

By default, the AppServiceProvider is fairly empty. This provider is a great place to add your application’s own bootstrapping and service container bindings. Of course, for large applications, you may wish to create several service providers, each with a more granular type of bootstrapping.

Laravel Deployment

When you’re ready to deploy your Laravel application to production, there are some important things you can do to make sure your application is running as efficiently as possible. In this document, we’ll cover some great starting points for making sure your Laravel application is deployed properly.
デプロイについて言及。deployって、単にgit pullでいいんちゃう?

Server Configuration
Nginx
If you are deploying your application to a server that is running Nginx, you may use the following configuration file as a starting point for configuring your web server. Most likely, this file will need to be customized depending on your server’s configuration. If you would like assistance in managing your server, consider using a service such as Laravel Forge:

server {
    listen 80;
    server_name example.com;
    root /example.com/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.html index.htm index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

nginxだと、routingとは別に設定するのね。

Optimization
Autoloader Optimization
When deploying to production, make sure that you are optimizing Composer’s class autoloader map so Composer can quickly find the proper file to load for a given class:

composer install –optimize-autoloader –no-dev
Tip!! In addition to optimizing the autoloader, you should always be sure to include a composer.lock file in your project’s source control repository. Your project’s dependencies can be installed much faster when a composer.lock file is present.

Optimizing Configuration Loading
When deploying your application to production, you should make sure that you run the config:cache Artisan command during your deployment process:

php artisan config:cache
This command will combine all of Laravel’s configuration files into a single, cached file, which greatly reduces the number of trips the framework must make to the filesystem when loading your configuration values.

Note: If you execute the config:cache command during your deployment process, you should be sure that you are only calling the env function from within your configuration files. Once the configuration has been cached, the .env file will not be loaded and all calls to the env function will return null.

Deploying With Forge
If you aren’t quite ready to manage your own server configuration or aren’t comfortable configuring all of the various services needed to run a robust Laravel application, Laravel Forge is a wonderful alternative.

Laravel Forge can create servers on various infrastructure providers such as DigitalOcean, Linode, AWS, and more. In addition, Forge installs and manages all of the tools needed to build robust Laravel applications, such as Nginx, MySQL, Redis, Memcached, Beanstalk, and more.
forgeとは仕事場。
nginx使う場合は設定が必要ということがわかった。

Laravel valet

valetって何? 一般的にはボーイという意味。

Valet is a Laravel development environment for Mac minimalists. No Vagrant, no /etc/hosts file. You can even share your sites publicly using local tunnels. Yeah, we like it too.

Laravel Valet configures your Mac to always run Nginx in the background when your machine starts. Then, using DnsMasq, Valet proxies all requests on the *.test domain to point to sites installed on your local machine.

In other words, a blazing fast Laravel development environment that uses roughly 7 MB of RAM. Valet isn’t a complete replacement for Vagrant or Homestead, but provides a great alternative if you want flexible basics, prefer extreme speed, or are working on a machine with a limited amount of RAM.

Out of the box, Valet support includes, but is not limited to:
vagrantではないけど、環境構築のようです。

Laravel
Lumen
Bedrock
CakePHP 3
Concrete5
Contao
Craft
Drupal
Jigsaw
Joomla
Katana
Kirby
Magento
OctoberCMS
Sculpin
Slim
Statamic
Static HTML
Symfony
WordPress
Zend
フレームワーク、wordpress, zend, cake, symfonyあたりは触ってます。
However, you may extend Valet with your own custom drivers.

Valet Or Homestead
As you may know, Laravel offers Homestead, another local Laravel development environment. Homestead and Valet differ in regards to their intended audience and their approach to local development. Homestead offers an entire Ubuntu virtual machine with automated Nginx configuration. Homestead is a wonderful choice if you want a fully virtualized Linux development environment or are on Windows / Linux.

Valet only supports Mac, and requires you to install PHP and a database server directly onto your local machine. This is easily achieved by using Homebrew with commands like brew install php and brew install mysql. Valet provides a blazing fast local development environment with minimal resource consumption, so it’s great for developers who only require PHP / MySQL and do not need a fully virtualized development environment.

Both Valet and Homestead are great choices for configuring your Laravel development environment. Which one you choose will depend on your personal taste and your team’s needs.

Installation
Valet requires macOS and Homebrew. Before installation, you should make sure that no other programs such as Apache or Nginx are binding to your local machine’s port 80.

Install or update Homebrew to the latest version using brew update.
Install PHP 7.2 using Homebrew via brew install php@7.2.
Install Composer.
Install Valet with Composer via composer global require laravel/valet. Make sure the ~/.composer/vendor/bin directory is in your system’s “PATH”.
Run the valet install command. This will configure and install Valet and DnsMasq, and register Valet’s daemon to launch when your system starts.
Once Valet is installed, try pinging any *.test domain on your terminal using a command such as ping foobar.test. If Valet is installed correctly you should see this domain responding on 127.0.0.1.

Valet will automatically start its daemon each time your machine boots. There is no need to run valet start or valet install ever again once the initial Valet installation is complete.

Using Another Domain
By default, Valet serves your projects using the .test TLD. If you’d like to use another domain, you can do so using the valet domain tld-name command.

For example, if you’d like to use .app instead of .test, run valet domain app and Valet will start serving your projects at *.app automatically.

Database
If you need a database, try MySQL by running brew install mysql@5.7 on your command line. Once MySQL has been installed, you may start it using the brew services start mysql@5.7 command. You can then connect to the database at 127.0.0.1 using the root username and an empty string for the password.

Upgrading
You may update your Valet installation using the composer global update command in your terminal. After upgrading, it is good practice to run the valet install command so Valet can make additional upgrades to your configuration files if necessary.

Upgrading To Valet 2.0
Valet 2.0 transitions Valet’s underlying web server from Caddy to Nginx. Before upgrading to this version you should run the following commands to stop and uninstall the existing Caddy daemon:

valet stop
valet uninstall
Next, you should upgrade to the latest version of Valet. Depending on how you installed Valet, this is typically done through Git or Composer. If you installed Valet via Composer, you should use the following command to update to the latest major version:

composer global require laravel/valet
Once the fresh Valet source code has been downloaded, you should run the install command:

valet install
valet restart
After upgrading, it may be necessary to re-park or re-link your sites
ふーん、valetね。やはりmac環境ですな。

Serving Sites
Once Valet is installed, you’re ready to start serving sites. Valet provides two commands to help you serve your Laravel sites: park and link.

The park Command

Create a new directory on your Mac by running something like mkdir ~/Sites. Next, cd ~/Sites and run valet park. This command will register your current working directory as a path that Valet should search for sites.
Next, create a new Laravel site within this directory: laravel new blog.
Open http://blog.test in your browser.

To see a listing of all of your linked directories, run the valet links command. You may use valet unlink app-name to destroy the symbolic link.

Tip!! You can use valet link to serve the same project from multiple (sub)domains. To add a subdomain or another domain to your project run valet link subdomain.app-name from the project folder.

Securing Sites With TLS

By default, Valet serves sites over plain HTTP. However, if you would like to serve a site over encrypted TLS using HTTP/2, use the secure command. For example, if your site is being served by Valet on the laravel.test domain, you should run the following command to secure it:

valet secure laravel
To “unsecure” a site and revert back to serving its traffic over plain HTTP, use the unsecure command. Like the secure command, this command accepts the host name that you wish to unsecure:

valet unsecure laravel
Sharing Sites
Valet even includes a command to share your local sites with the world. No additional software installation is required once Valet is installed.

To share a site, navigate to the site’s directory in your terminal and run the valet share command. A publicly accessible URL will be inserted into your clipboard and is ready to paste directly into your browser. That’s it.

To stop sharing your site, hit Control + C to cancel the process.

Note: valet share does not currently support sharing sites that have been secured using the valet secure command.
なるほど、こういうこともできるのね。

Custom Valet Drivers
You can write your own Valet “driver” to serve PHP applications running on another framework or CMS that is not natively supported by Valet. When you install Valet, a ~/.config/valet/Drivers directory is created which contains a SampleValetDriver.php file. This file contains a sample driver implementation to demonstrate how to write a custom driver. Writing a driver only requires you to implement three methods: serves, isStaticFile, and frontControllerPath.

All three methods receive the $sitePath, $siteName, and $uri values as their arguments. The $sitePath is the fully qualified path to the site being served on your machine, such as /Users/Lisa/Sites/my-project. The $siteName is the “host” / “site name” portion of the domain (my-project). The $uri is the incoming request URI (/foo/bar).

Once you have completed your custom Valet driver, place it in the ~/.config/valet/Drivers directory using the FrameworkValetDriver.php naming convention. For example, if you are writing a custom valet driver for WordPress, your file name should be WordPressValetDriver.php.

Let’s take a look at a sample implementation of each method your custom Valet driver should implement.

The serves Method
The serves method should return true if your driver should handle the incoming request. Otherwise, the method should return false. So, within this method you should attempt to determine if the given $sitePath contains a project of the type you are trying to serve.

For example, let’s pretend we are writing a WordPressValetDriver. Our serves method might look something like this:

The isStaticFile Method
The isStaticFile should determine if the incoming request is for a file that is “static”, such as an image or a stylesheet. If the file is static, the method should return the fully qualified path to the static file on disk. If the incoming request is not for a static file, the method should return false:

laravel ports

by default, the following ports are forwarded to your Homestead environment:

SSH: 2222 → Forwards To 22
ngrok UI: 4040 → Forwards To 4040
HTTP: 8000 → Forwards To 80
HTTPS: 44300 → Forwards To 443
MySQL: 33060 → Forwards To 3306
PostgreSQL: 54320 → Forwards To 5432
MongoDB: 27017 → Forwards To 27017
Mailhog: 8025 → Forwards To 8025
Minio: 9600 → Forwards To 9600

22, 80, 443は基本。3306, 5432, 27017とか、DBであるんだな。

Forwarding Additional Ports
If you wish, you may forward additional ports to the Vagrant box, as well as specify their protocol:

ports:
– send: 50000
to: 5000
– send: 7777
to: 777
protocol: udp

Sharing Your Environment
Sometimes you may wish to share what you’re currently working on with coworkers or a client. Vagrant has a built-in way to support this via vagrant share; however, this will not work if you have multiple sites configured in your Homestead.yaml file.

To solve this problem, Homestead includes its own share command. To get started, SSH into your Homestead machine via vagrant ssh and run share homestead.test. This will share the homestead.test site from your Homestead.yaml configuration file. Of course, you may substitute any of your other configured sites for homestead.test:

share homestead.test
After running the command, you will see an Ngrok screen appear which contains the activity log and the publicly accessible URLs for the shared site. If you would like to specify a custom region, subdomain, or other Ngrok runtime option, you may add them to your share command:

share homestead.test -region=eu -subdomain=laravel
Note: Remember, Vagrant is inherently insecure and you are exposing your virtual machine to the Internet when running the share command.

Multiple PHP Versions
Homestead 6 introduced support for multiple versions of PHP on the same virtual machine. You may specify which version of PHP to use for a given site within your Homestead.yaml file. The available PHP versions are: “5.6”, “7.0”, “7.1”, “7.2” and “7.3” (the default):
laravelは確か7.1以上だったが、5.6とかもOKなんだ。

In addition, you may use any of the supported PHP versions via the CLI:

php5.6 artisan list
php7.0 artisan list
php7.1 artisan list
php7.2 artisan list
php7.3 artisan list

Web Servers
Homestead uses the Nginx web server by default. However, it can install Apache if apache is specified as a site type. While both web servers can be installed at the same time, they cannot both be running at the same time. The flip shell command is available to ease the process of switching between web servers. The flip command automatically determines which web server is running, shuts it off, and then starts the other server. To use this command, SSH into your Homestead machine and run the command in your terminal:

flip

Mail
Homestead includes the Postfix mail transfer agent, which is listening on port 1025 by default. So, you may instruct your application to use the smtp mail driver on localhost port 1025. Then, all sent mail will be handled by Postfix and caught by Mailhog. To view your sent emails, open http://localhost:8025 in your web browser.

Extending Homestead
You may extend Homestead using the after.sh script in the root of your Homestead directory. Within this file, you may add any shell commands that are necessary to properly configure and customize your virtual machine.

When customizing Homestead, Ubuntu may ask you if you would like to keep a package’s original configuration or overwrite it with a new configuration file. To avoid this, you should use the following command when installing packages to avoid overwriting any configuration previously written by Homestead:

sudo apt-get -y \
-o Dpkg::Options::=”–force-confdef” \
-o pkg::Options::=”–force-confold” \
install your-package
Updating Homestead
You can update Homestead in two simple steps. First, you should update the Vagrant box using the vagrant box update command:

vagrant box update
Next, you need to update the Homestead source code. If you cloned the repository you can git pull origin master at the location you originally cloned the repository.

If you have installed Homestead via your project’s composer.json file, you should ensure your composer.json file contains “laravel/homestead”: “^7” and update your dependencies:

composer update
Provider Specific Settings
VirtualBox
natdnshostresolver
By default, Homestead configures the natdnshostresolver setting to on. This allows Homestead to use your host operating system’s DNS settings. If you would like to override this behavior, add the following lines to your Homestead.yaml file:

provider: virtualbox
natdnshostresolver: off
Symbolic Links On Windows
If symbolic links are not working properly on your Windows machine, you may need to add the following block to your Vagrantfile:

config.vm.provider “virtualbox” do |v|
v.customize [“setextradata”, :id, “VBoxInternal2/SharedFoldersEnableSymlinksCreate/v-root”, “1”]
end

やっと終わったー、最後はやや雑だが。。

laravel Environment Variables

You can set global environment variables by adding them to your Homestead.yaml file:

variables:
– key: APP_ENV
value: local
– key: FOO
value: bar
After updating the Homestead.yaml, be sure to re-provision the machine by running vagrant reload –provision. This will update the PHP-FPM configuration for all of the installed PHP versions and also update the environment for the vagrant user.

Configuring Cron Schedules
Laravel provides a convenient way to schedule Cron jobs by scheduling a single schedule:run Artisan command to be run every minute. The schedule:run command will examine the job schedule defined in your App\Console\Kernel class to determine which jobs should be run.

If you would like the schedule:run command to be run for a Homestead site, you may set the schedule option to true when defining the site:
sites:
– map: homestead.test
to: /home/vagrant/code/Laravel/public
schedule: true
The Cron job for the site will be defined in the /etc/cron.d folder of the virtual machine.
cron.d って、くろんタブですな。

Configuring Mailhog
Mailhog allows you to easily catch your outgoing email and examine it without actually sending the mail to its recipients. To get started, update your .env file to use the following mail settings:

MAIL_DRIVER=smtp
MAIL_HOST=localhost
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
Once Mailhog has been configured, you may access the Mailhog dashboard at http://localhost:8025
driverはsmtp

Configuring Minio
Minio is an open source object storage server with an Amazon S3 compatible API. To install Minio, update your Homestead.yaml file with the following configuration option:

minio: true
By default, Minio is available on port 9600. You may access the Minio control panel by visiting http://homestead:9600/. The default access key is homestead, while the default secret key is secretkey. When accessing Minio, you should always use region us-east-1.

In order to use Minio you will need to adjust the S3 disk configuration in your config/filesystems.php configuration file. You will need to add the use_path_style_endpoint option to the disk configuration, as well as change the url key to endpoint:
minio? 知らんぞ

's3' => [
    'driver' => 's3',
    'key' => env('AWS_ACCESS_KEY_ID'),
    'secret' => env('AWS_SECRET_ACCESS_KEY'),
    'region' => env('AWS_DEFAULT_REGION'),
    'bucket' => env('AWS_BUCKET'),
    'endpoint' => env('AWS_URL'),
    'use_path_style_endpoint' => true
]

あーs3だ。

inally, ensure your .env file has the following options:

AWS_ACCESS_KEY_ID=homestead
AWS_SECRET_ACCESS_KEY=secretkey
AWS_DEFAULT_REGION=us-east-1
AWS_URL=http://homestead:9600
To provision buckets, add a buckets directive to your Homestead configuration file:

buckets:
– name: your-bucket
policy: public
– name: your-private-bucket
policy: none
Supported policy values include: none, download, upload, and public.
ok,ok

Installing Neo4j

Neo4j is a graph database management system. To install Neo4j Community Edition, update your Homestead.yaml file with the following configuration option:

neo4j: true
The default Neo4j installation will set the database username to homestead and corresponding password to secret. To access the Neo4j browser, visit http://homestead.test:7474 via your web browser. The ports 7687 (Bolt), 7474 (HTTP), and 7473 (HTTPS) are ready to serve requests from the Neo4j client.

なんだこれ、聞いたことねーぞ
サイトを見てみる。

The Neo4j Graph Platform – The #1 Platform for Connected Data

ああ、好きな人は好きだよね。これ。とりあえず進もう。
Aliases
You may add Bash aliases to your Homestead machine by modifying the aliases file within your Homestead directory:

alias c=’clear’
alias ..=’cd ..’
After you have updated the aliases file, you should re-provision the Homestead machine using the vagrant reload –provision command. This will ensure that your new aliases are available on the machine.
これでやっと半分くらい。

Daily Usage
Accessing Homestead Globally
Sometimes you may want to vagrant up your Homestead machine from anywhere on your filesystem. You can do this on Mac / Linux systems by adding a Bash function to your Bash profile. On Windows, you may accomplish this by adding a “batch” file to your PATH. These scripts will allow you to run any Vagrant command from anywhere on your system and will automatically point that command to your Homestead installation:

Mac / Linux
function homestead() {
( cd ~/Homestead && vagrant $* )
}
Make sure to tweak the ~/Homestead path in the function to the location of your actual Homestead installation. Once the function is installed, you may run commands like homestead up or homestead ssh from anywhere on your system.

Windows
Create a homestead.bat batch file anywhere on your machine with the following contents:

Make sure to tweak the example C:\Homestead path in the script to the actual location of your Homestead installation. After creating the file, add the file location to your PATH. You may then run commands like homestead up or homestead ssh from anywhere on your system.
うん、OK

Connecting Via SSH
You can SSH into your virtual machine by issuing the vagrant ssh terminal command from your Homestead directory.

But, since you will probably need to SSH into your Homestead machine frequently, consider adding the “function” described above to your host machine to quickly SSH into the Homestead box.
ssh接続のportは22でしたね。

scp
SSHを使用してリモートホストとの間でファイルを転送を行う。
ssh-keygen
公開鍵認証方式で使用するキーペアを生成する。
ssh-copy-id
公開鍵をリモートホストに登録するコマンド。環境によってはインストールされていない場合がある。

Connecting To Databases
A homestead database is configured for both MySQL and PostgreSQL out of the box. For even more convenience, Laravel’s .env file configures the framework to use this database out of the box.

To connect to your MySQL or PostgreSQL database from your host machine’s database client, you should connect to 127.0.0.1 and port 33060 (MySQL) or 54320 (PostgreSQL). The username and password for both databases is homestead / secret.

mysqlは33060のよう。
Port 33060 Details
https://www.speedguide.net/port.php?port=33060
33060 udp games Wolfenstein uses ports 33060-33070, developer: Raven Software SG
33060 tcp mysqlx MySQL Database Extended Interface (IANA official)
あ、こりゃすげーわ。

Database Backups
Homestead can automatically backup your database when your Vagrant box is destroyed. To utilize this feature, you must be using Vagrant 2.1.0 or greater. Or, if you are using an older version of Vagrant, you must install the vagrant-triggers plug-in. To enable automatic database backups, add the following line to your Homestead.yaml file:

backup: true
Once configured, Homestead will export your databases to mysql_backup and postgres_backup directories when the vagrant destroy command is executed. These directories can be found in the folder where you cloned Homestead or in the root of your project if you are using the per project installation method.

Adding Additional Sites
Once your Homestead environment is provisioned and running, you may want to add additional Nginx sites for your Laravel applications. You can run as many Laravel installations as you wish on a single Homestead environment. To add an additional site, add the site to your Homestead.yaml file:

sites:
– map: homestead.test
to: /home/vagrant/code/Laravel/public
– map: another.test
to: /home/vagrant/code/another/public
If Vagrant is not automatically managing your “hosts” file, you may need to add the new site to that file as well:

192.168.10.10 homestead.test
192.168.10.10 another.test
Once the site has been added, run the vagrant reload –provision command from your Homestead directory.

Site Types
Homestead supports several types of sites which allow you to easily run projects that are not based on Laravel. For example, we may easily add a Symfony application to Homestead using the symfony2 site type:

sites:
– map: symfony2.test
to: /home/vagrant/code/Symfony/web
type: “symfony2”
おう、なんかsymfonyやたらでてくんなー

laravel Elastic search

Installing Elasticsearch
To install Elasticsearch, add the elasticsearch option to your Homestead.yaml file and specify a supported version, which may be a major version or an exact version number (major.minor.patch). The default installation will create a cluster named ‘homestead’. You should never give Elasticsearch more than half of the operating system’s memory, so make sure your Homestead machine has at least twice the Elasticsearch allocation:

Elasticsearchとは?
Elasticsearch は Elastic 社が開発しているオープンソースの全文検索エンジン。
大量のドキュメントから目的の単語を含むドキュメントを高速に抽出することができる。
RESTful インターフェースを使って操作

Elasticsearch ドキュメントを保存・検索します。
Kibana データを可視化します。
Logstash データソースからデータを取り込み・変換します。
Beats データソースからデータを取り込みます。
X-Pack セキュリティ、モニタリング、ウォッチ、レポート、グラフの機能を拡張します。

java

Laravel Per Project Installation

Instead of installing Homestead globally and sharing the same Homestead box across all of your projects, you may instead configure a Homestead instance for each project you manage. Installing Homestead per project may be beneficial if you wish to ship a Vagrantfile with your project, allowing others working on the project to vagrant up.

To install Homestead directly into your project, require it using Composer:

Once Homestead has been installed, use the make command to generate the Vagrantfile and Homestead.yaml file in your project root. The make command will automatically configure the sites and folders directives in the Homestead.yaml file.

Mac / Linux:

php vendor/bin/homestead make
Windows:

vendor\\bin\\homestead make
Next, run the vagrant up command in your terminal and access your project at http://homestead.test in your browser. Remember, you will still need to add an /etc/hosts file entry for homestead.test or the domain of your choice.
なるほど、vagrant構築手順か。

Installing MariaDB
If you prefer to use MariaDB instead of MySQL, you may add the mariadb option to your Homestead.yaml file. This option will remove MySQL and install MariaDB. MariaDB serves as a drop-in replacement for MySQL so you should still use the mysql database driver in your application’s database configuration:
MariaDBも使えるとのこと。使ったことないぞ。

box: laravel/homestead
ip: “192.168.10.10”
memory: 2048
cpus: 4
provider: virtualbox
mariadb: true