vagrant でcake3.5 のローカル環境構築

# Vagrant とは

vagrant とはvartual box での環境構築簡単にしてくれるラッパーツールらしいっす

便利です。

なので使います。

PHP の場合ビルトインサーバなるものも使えますが、こちらの方がvartual box完結できるのでなにかといいので採用

vagrant をインストします。

下記よりダウンロードを行います。

https://www.vagrantup.com/

virtual box のインストは下記から、OSを 選択して入手

https://www.virtualbox.org/wiki/Downloads

それぞれインストーラが同梱されているので、それを使ってインストール行う。

vagrant 用のディレクトリーを作成

```
mkdir vmdir
cd vmdir
```

作成したディレクトリーにてvagrant ファイルを作成します。

下記実行
```
vagrant init
```

下記ログが出力されます。

```
Vagrant failed to initialize at a very early stage:

The plugins failed to initialize correctly. This may be due to manual
modifications made within the Vagrant home directory. Vagrant can
attempt to automatically correct this issue by running:

  vagrant plugin repair

If Vagrant was recently updated, this error may be due to incompatible
versions of dependencies. To fix this problem please remove and re-install
all plugins. Vagrant can attempt to do this automatically by running:

  vagrant plugin expunge --reinstall

Or you may want to try updating the installed plugins to their latest
versions:

  vagrant plugin update

Error message given during initialization: Unable to resolve dependency: user requested 'vagrant-hostsupdater (> 0)'
```

私の場合は下記にて解決

```
vagrant plugin repair
Repairing currently installed plugins. This may take a few minutes...
Fetching: vagrant-hostsupdater-1.0.2.gem (100%)
Fetching: vagrant-share-1.1.9.gem (100%)
Installed plugins successfully repaired!
```

それでも解決しない場合はVagrant のドキュメントをみてください。

今回はcentOS 6.9をインストしたいので下記実行
```
vagrant box add bento/centos-6.9

==> box: Loading metadata for box 'bento/centos-6.9'
    box: URL: https://vagrantcloud.com/bento/centos-6.9
This box can work with multiple providers! The providers that it
can work with are listed below. Please review the list and choose
the provider you will be working with.

1) parallels
2) virtualbox
3) vmware_desktop

```
三択、選択しろとのことなので、
私の場合はVirtualboxでやりたいので、

2 <= 選択

```
Enter your choice: 2
==> box: Adding box 'bento/centos-6.9' (v201708.22.0) for provider: virtualbox
    box: Downloading: https://vagrantcloud.com/bento/boxes/centos-6.9/versions/201708.22.0/providers/virtualbox.box
==> box: Box download is resuming from prior download progress
==> box: Successfully added box 'bento/centos-6.9' (v201708.22.0) for 'virtualbox'!
```

成功しました。

リストに追加されたか確認します。

下記実行

```
vagrant box list
bento/centos-6.9 (virtualbox, 201708.22.0)
miya0001/vccw    (virtualbox, 2.19.0)
```
入ってます、弁当食いたくなります、

```
vagrant up
```
上記実行で環境構築完了

sshで入ってみます。

```
vagrant ssh
[vagrant@localhost ~]$ ls -a
.  ..  .bash_logout  .bash_profile  .bashrc  .ssh  .vbox_version
```

入れました。

# PHP インストール

```
sudo yum install -y epel-release
sudo rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
sudo yum install --enablerepo=remi --enablerepo=remi-php56 -y php php-opcache php-devel php-mbstring php-mcrypt php-mysqlnd php-phpunit-PHPUnit php-pecl-xdebug php-pecl-xhprof
sudo yum install --enablerepo=remi --enablerepo=remi-php56 -y php-intl
```

php intlが必要なので存在確認

```
php -m | grep intl
intl
```

いました。


php.ini編集

```
sudo vim /etc/php.ini
date.timzone = "Asia/Tokyo"
```
を追記、

# Apache をインストール

```
sudo yum install -y httpd httpd-devel
sudo service httpd start
sudo chkconfig httpd on
```

ログアウトし
Vagrantfile  左記編集

```
vim Vagrantfile 

config.vm.network "forwarded_port", guest: 80, host: 8080 左記がコメントアウトになっているので、コメントを外します。
```

vagrant をリロードします。

```
vagrant reload
```

http://127.0.0.1:8080/

これでapache のwelcome 画面が表示されてると思われます。

Composer がPHPのパッケージ管理システムが便利なので使います。

composer curlでインストール下記実行
```
 curl -s https://getcomposer.org/installer | php
```
/usr/local/bin

に配置します。

```
sudo mv composer.phar /usr/local/bin/composer
```

ドキュメントルートに移動します。

```
cd /var/www/html
composer create-project --prefer-dist cakephp/app ./
Installing cakephp/app (3.5.0)
  - Installing cakephp/app (3.5.0): Downloading (100%)         
Created project in ./
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 39 installs, 0 updates, 0 removals
  - Installing cakephp/plugin-installer (1.0.0): Downloading (100%)         
  - Installing aura/intl (3.0.0): Downloading (100%)         
  - Installing mobiledetect/mobiledetectlib (2.8.26): Downloading (100%)         
  - Installing psr/http-message (1.0.1): Downloading (100%)         
  - Installing zendframework/zend-diactoros (1.6.0): Downloading (100%)         
  - Installing psr/log (1.0.2): Downloading (100%)         
  - Installing cakephp/chronos (1.1.2): Downloading (100%)         
  - Installing cakephp/cakephp (3.5.2): Downloading (100%)         
  - Installing symfony/polyfill-mbstring (v1.5.0): Downloading (100%)         
  - Installing symfony/yaml (v3.3.9): Downloading (100%)         
  - Installing symfony/debug (v3.3.9): Downloading (100%)         
  - Installing symfony/console (v3.3.9): Downloading (100%)         
  - Installing symfony/filesystem (v3.3.9): Downloading (100%)         
  - Installing symfony/config (v3.3.9): Downloading (100%)         
  - Installing robmorgan/phinx (v0.8.1): Downloading (100%)         
  - Installing cakephp/migrations (1.7.1): Downloading (100%)         
  - Installing m1/env (2.1.0): Downloading (100%)         
  - Installing josegonzalez/dotenv (2.1.0): Downloading (100%)         
  - Installing jakub-onderka/php-console-color (0.1): Downloading (100%)         
  - Installing jakub-onderka/php-console-highlighter (v0.3.2): Downloading (100%)         
  - Installing dnoegel/php-xdg-base-dir (0.1): Downloading (100%)         
  - Installing nikic/php-parser (v3.1.1): Downloading (100%)         
  - Installing symfony/var-dumper (v3.3.9): Downloading (100%)         
  - Installing psy/psysh (v0.8.11): Downloading (100%)         
  - Installing jdorn/sql-formatter (v1.2.17): Downloading (100%)         
  - Installing symfony/process (v3.3.9): Downloading (100%)         
  - Installing symfony/finder (v3.3.9): Downloading (100%)         
  - Installing seld/phar-utils (1.0.1): Downloading (100%)         
  - Installing seld/jsonlint (1.6.1): Downloading (100%)         
  - Installing seld/cli-prompt (1.0.3): Downloading (100%)         
  - Installing justinrainbow/json-schema (5.2.1): Downloading (100%)         
  - Installing composer/spdx-licenses (1.1.6): Downloading (100%)         
  - Installing composer/semver (1.4.2): Downloading (100%)         
  - Installing composer/ca-bundle (1.0.8): Downloading (100%)         
  - Installing composer/composer (1.5.2): Downloading (100%)         
  - Installing cakephp/debug_kit (3.11.1): Downloading (100%)         
  - Installing cakephp/bake (1.4.2): Downloading (100%)         
  - Installing squizlabs/php_codesniffer (3.0.2): Downloading (100%)         
  - Installing cakephp/cakephp-codesniffer (3.0.1): Downloading (100%)         
cakephp/app suggests installing markstory/asset_compress (An asset compression plugin which provides file concatenation and a flexible filter system for preprocessing and minification.)
cakephp/app suggests installing dereuromark/cakephp-ide-helper (After baking your code, this keeps your annotations in sync with the code evolving from there on for maximum IDE and PHPStan compatibility.)
cakephp/app suggests installing phpunit/phpunit (Allows automated tests to be run without system-wide install.)
cakephp/cakephp suggests installing lib-ICU (The intl PHP library, to use Text::transliterate() or Text::slug())
symfony/console suggests installing symfony/event-dispatcher ()
m1/env suggests installing m1/vars (For loading of configs)
symfony/var-dumper suggests installing ext-symfony_debug ()
psy/psysh suggests installing ext-pdo-sqlite (The doc command requires SQLite to work.)
psy/psysh suggests installing hoa/console (A pure PHP readline implementation. You'll want this if your PHP install doesn't already support readline or libedit.)
cakephp/debug_kit suggests installing ext-sqlite (DebugKit needs to store panel data in a database. SQLite is simple and easy to use.)
Writing lock file
Generating autoload files
> Cake\Composer\Installer\PluginInstaller::postAutoloadDump
> App\Console\Installer::postInstall
Created `config/app.php` file
Set Folder Permissions ? (Default to Y) [Y,n]? Y # <- Yを選択
Permissions set on /var/www/html/tmp/cache
Permissions set on /var/www/html/tmp/cache/models
Permissions set on /var/www/html/tmp/cache/persistent
Permissions set on /var/www/html/tmp/cache/views
Permissions set on /var/www/html/tmp/sessions
Permissions set on /var/www/html/tmp/tests
Permissions set on /var/www/html/tmp
Permissions set on /var/www/html/logs
Updated Security.salt value in config/app.php
```
# Apache のconfファイルを編集します。

```
sudo vi /etc/httpd/conf/httpd.conf

#    下記変更
#    Options Indexes FollowSymLinks
     Options Includes ExecCGI FollowSymLinks
#    下記変更
#    AllowOverride None
     AllowOverride All

# 下記も変更
<Directory "/var/www/icons">
#    Options Indexes MultiViews FollowSymLinks
    Options MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

# 最後の行へ追加
TraceEnable off

```

Apacheを再起動

```
sudo service httpd restart
Stopping httpd:                                            [  OK  ]
Starting httpd: httpd: Could not reliably determine the server's fully qualified domain name, using localhost.localdomain for ServerName
                                                           [  OK  ]
```

ブラウザーで見れるか確認します。

mysql を入れます。

```
vagrant~:$: 
->> sudo yum install mysql mysql-server mysql-devel -y
vagrant~:$: 
->> sudo service mysqld start
vagrant/:$: 
->> sudo chkconfig mysqld on
vagrant~:$: 
->> mysql_secure_installation



NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MySQL to secure it, we'll need the current
password for the root user.  If you've just installed MySQL, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none): 
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
Enter current password for root (enter for none): 
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MySQL
root user without the proper authorisation.

Set root password? [Y/n] Y
New password: 
Re-enter new password: 
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MySQL installation has an anonymous user, allowing anyone
to log into MySQL without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] Y
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] Y
 ... Success!

By default, MySQL comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] Y
 - Dropping test database...
ERROR 1008 (HY000) at line 1: Can't drop database 'test'; database doesn't exist
 ... Failed!  Not critical, keep moving...
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] Y
 ... Success!




All done!  If you've completed all of the above steps, your MySQL
installation should now be secure.

Thanks for using MySQL!


Cleaning up...

```

mysqlユーザー作成

```
mysql -u root -p
mysql> grant all privileges on *.* to my_app@localhost identified by 'password';
Query OK, 0 rows affected (0.02 sec)

mysql> exit
Bye

```

先ほど作成したユーザーでログインします。
databaseを作成します。

```

vagrant~:$: 
->> mysql -u my_app -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 16
Server version: 5.6.37 MySQL Community Server (GPL)

Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create database if not exists cakeDB;
Query OK, 1 row affected (0.00 sec)

```

データーベースを作成したら、

cakePHPのconfig -> app.phpを編集します。

```
'Datasources' => [
        'default' => [
            'className' => 'Cake\Database\Connection',
            'driver' => 'Cake\Database\Driver\Mysql',
            'persistent' => false,
            'host' => 'localhost',
            /**
             * CakePHP will use the default DB port based on the driver selected
             * MySQL on MAMP uses port 8889, MAMP users will want to uncomment
             * the following line and set the port accordingly
             */
            //'port' => 'non_standard_port_number',
            'username' => 'my_app', <- my_app　cake php のユーザー名を記述
            'password' => 'DBのパスワードを記述',
            'database' => '接続したいDatabaseを記述',
            'encoding' => 'utf8',
            'timezone' => '+09:00',
            'flags' => [],
            'cacheMetadata' => true,
            'log' => false,


```

これでチュートリアルページのdatabase の項目が緑色になってれば成功。

![スクリーンショット 2017-09-16 17.25.04.png](https://qiita-image-store.s3.amazonaws.com/0/31394/fb21e67e-9a99-4f64-6901-b8d56c1f14e0.png)