Vagrant に Yii2.0 を構築する


## 前提条件

OS：CentOS7.0
Vagrant：1.8.6
VirtualBox：5.1.6

## PHP

### PHP7.0をインストールする

```
[vagrant@localhost ~]$ sudo yum -y install epel-release
[vagrant@localhost ~]$ sudo rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-7.rpm
[vagrant@localhost ~]$ sudo yum -y install --enablerepo=remi,remi-php70 php php-devel php-mbstring php-pdo php-gd php-openssl php-xml
```

### php.ini を初期設定する

```
[vagrant@localhost ~]$ sudo sed -i -e "s|;error_log = syslog|error_log = /var/log/php.log|" /etc/php.ini
[vagrant@localhost ~]$ sudo sed -i -e "s|;mbstring.language = Japanese|mbstring.language = Japanese|" /etc/php.ini
[vagrant@localhost ~]$ sudo sed -i -e "s|;mbstring.internal_encoding = EUC-JP|mbstring.internal_encoding = UTF-8|" /etc/php.ini
[vagrant@localhost ~]$ sudo sed -i -e "s|;mbstring.http_input = auto|mbstring.http_input = auto|" /etc/php.ini
[vagrant@localhost ~]$ sudo sed -i -e "s|;mbstring.detect_order = auto|mbstring.detect_order = auto|" /etc/php.ini
[vagrant@localhost ~]$ sudo sed -i -e "s|expose_php = On|expose_php = Off|" /etc/php.ini
[vagrant@localhost ~]$ sudo sed -i -e "s|;date.timezone =|date.timezone = Asia/Tokyo|" /etc/php.ini
```

## Composerをインストールする

参考：[Installing via Composer](http://www.yiiframework.com/doc-2.0/guide-start-installation.html#installing-via-composer)

```
[vagrant@localhost ~]$ curl -sS https://getcomposer.org/installer | php
All settings correct for using Composer
Downloading 1.2.2...

Composer successfully installed to: /home/vagrant/composer.phar
Use it: php composer.phar

[vagrant@localhost ~]$ sudo mv composer.phar /usr/local/bin/composer
[vagrant@localhost ~]$ composer self-update
You are already using composer version 1.2.2 (stable channel).

```

```
[vagrant@localhost ~]$ composer global require "fxp/composer-asset-plugin:^1.2.0"
Changed current directory to /home/vagrant/.config/composer
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing fxp/composer-asset-plugin (v1.2.2)
    Downloading: 100%         

Writing lock file
Generating autoload files

```

## Yii

### Yii2.0をインストールする

参考：[Installing Yii](http://www.yiiframework.com/doc-2.0/guide-start-installation.html#installing-yii)

```
[vagrant@localhost ~]$ composer create-project --prefer-dist yiisoft/yii2-app-basic basic
Installing yiisoft/yii2-app-basic (2.0.10)
  - Installing yiisoft/yii2-app-basic (2.0.10)
    Downloading: Connecting...
    Downloading: 100%         

Created project in basic
Loading composer repositories with package information
Updating dependencies (including require-dev)
Reading bower.json of bower-asset/jquery (1.12.1)       
Could not fetch https://api.github.com/repos/jquery/jquery-dist/commits/56ead6ffbf8560c521e7e94518d35db42b19f5f3, please create a GitHub OAuth token to go over the API rate limit
Head to https://github.com/settings/tokens/new?scopes=repo&description=Composer+on+localhost.localdomain+2016-11-22+1528
to retrieve a token. It will be stored in "/home/vagrant/.config/composer/auth.json" for future use by Composer.
Token (hidden): 
No token given, aborting.
You can also add it manually later by using "composer config github-oauth.github.com <token>"
Reading bower.json of bower-asset/jquery (1.12.0)
Could not fetch https://api.github.com/repos/jquery/jquery-dist/contents/bower.json?ref=efbdc6e3f0fa3d3cd4d3d8bfa37990b707f7c2e1, please create a GitHub OAuth token to go over the API rate limit
Head to https://github.com/settings/tokens/new?scopes=repo&description=Composer+on+localhost.localdomain+2016-11-22+1528
to retrieve a token. It will be stored in "/home/vagrant/.config/composer/auth.json" for future use by Composer.
Token (hidden): 

```

Githubの Setting -> Personal access tokens -> Generate new token でトークンを作成し、コピペする。

Token stored successfully. となる。

```
Token stored successfully.
  - Installing yiisoft/yii2-composer (2.0.4)               
    Downloading: 100%         

  - Installing swiftmailer/swiftmailer (v5.4.3)
    Downloading: 100%         

  - Installing bower-asset/jquery (2.2.4)
    Downloading: 100%         

  - Installing bower-asset/yii2-pjax (v2.0.6)
    Downloading: 100%         

  - Installing bower-asset/punycode (v1.3.2)
    Downloading: 100%         

  - Installing bower-asset/jquery.inputmask (3.2.7)
    Downloading: 100%         

・・・以降、インストールが正常に進めばこのまま終了する

symfony/browser-kit suggests installing symfony/process ()
symfony/event-dispatcher suggests installing symfony/dependency-injection ()
symfony/event-dispatcher suggests installing symfony/http-kernel ()
symfony/console suggests installing symfony/process ()
phpunit/php-code-coverage suggests installing ext-xdebug (>=2.4.0)
sebastian/global-state suggests installing ext-uopz (*)
phpunit/phpunit-mock-objects suggests installing ext-soap (*)
phpunit/phpunit suggests installing phpunit/php-invoker (~1.1)
phpunit/phpunit suggests installing ext-xdebug (*)
codeception/base suggests installing flow/jsonpath (For using JSONPath in REST module)
codeception/base suggests installing phpseclib/phpseclib (for SFTP option in FTP Module)
codeception/base suggests installing league/factory-muffin (For DataFactory module)
codeception/base suggests installing league/factory-muffin-faker (For Faker support in DataFactory module)
codeception/base suggests installing symfony/phpunit-bridge (For phpunit-bridge support)
Writing lock file
Generating autoload files
> yii\composer\Installer::postCreateProject
chmod('runtime', 0777)...done.
chmod('web/assets', 0777)...done.
chmod('yii', 0755)...done.

```

### インストール状態を確認する

```
[vagrant@localhost ~]$ ls
base.sh  basic  cleanup.sh  puppet.sh  vagrant.sh  virtualbox.sh  zerodisk.sh
[vagrant@localhost ~]$ ls basic
LICENSE.md       commands       controllers       runtime  web
README.md        composer.json  mail              tests    yii
assets           composer.lock  models            vendor   yii.bat
codeception.yml  config         requirements.php  views

```

requirements.php で、Yiiのインストール状況を確認できる。

```
[vagrant@localhost ~]$ php ./basic/requirements.php 

Yii Application Requirement Checker

This script checks if your server configuration meets the requirements
for running Yii application.
It checks if the server is running the right version of PHP,
if appropriate PHP extensions have been loaded, and if php.ini file settings are correct.

Check conclusion:
-----------------

PHP version: OK

Reflection extension: OK

PCRE extension: OK

SPL extension: OK

Ctype extension: OK

MBString extension: OK

OpenSSL extension: OK

Intl extension: WARNING!!!
Required by: Internationalization support
Memo: PHP Intl extension 1.0.2 or higher is required when you want to use advanced parameters formatting
        in Yii::t(), non-latin languages with Inflector::slug(),
        IDN-feature of
        EmailValidator or UrlValidator or the yii\i18n\Formatter class.

ICU version: WARNING!!!
Required by: Internationalization support
Memo: ICU 49.0 or higher is required when you want to use # placeholder in plural rules
        (for example, plural in
        
        Formatter::asRelativeTime()) in the yii\i18n\Formatter class. Your current ICU version is (ICU is missing).

ICU Data version: WARNING!!!
Required by: Internationalization support
Memo: ICU Data 49.1 or higher is required when you want to use # placeholder in plural rules
        (for example, plural in
        
        Formatter::asRelativeTime()) in the yii\i18n\Formatter class. Your current ICU Data version is (ICU Data is missing).

Fileinfo extension: OK

DOM extension: OK

PDO extension: OK

PDO SQLite extension: OK

PDO MySQL extension: WARNING!!!
Required by: All DB-related classes
Memo: Required for MySQL database.

PDO PostgreSQL extension: WARNING!!!
Required by: All DB-related classes
Memo: Required for PostgreSQL database.

Memcache extension: WARNING!!!
Required by: MemCache

GD PHP extension with FreeType support: OK

ImageMagick PHP extension with PNG support: WARNING!!!
Required by: Captcha
Memo: Either GD PHP extension with FreeType support or ImageMagick PHP extension with PNG support is required for image CAPTCHA.

Expose PHP: OK

PHP allow url include: OK

PHP mail SMTP: OK

------------------------------------------
Errors: 0   Warnings: 7   Total checks: 22

```

## Apache

### DocumentRootを変更する

参考：[Recommended Apache Configuration](http://www.yiiframework.com/doc-2.0/guide-start-installation.html#recommended-apache-configuration)

```/etc/httpd/conf/httpd.conf
#                                                                              
# DocumentRoot: The directory out of which you will serve your                 
# documents. By default, all requests are taken from this directory, but       
# symbolic links and aliases may be used to point to other locations.          
#                                                                              
#DocumentRoot "/var/www/html"                                                  
DocumentRoot "/home/vagrant/basic/web" # 変更する

# Further relax access to the default document root:                           
<Directory "/home/vagrant/basic/web"> # 追加する
    #                                                                          
    # Possible values for the Options directive are "None", "All",             
    # or any combination of:                                                   
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiView\
s                                                                              
    #                                                                          
    # Note that "MultiViews" must be named *explicitly* --- "Options All"      
    # doesn't give it to you.                                                  
    #                                                                          
    # The Options directive is both complicated and important.  Please see     
    # http://httpd.apache.org/docs/2.4/mod/core.html#options                   
    # for more information.                                                    
    #                                                                          
    Options Indexes FollowSymLinks

    #                                                                          
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:             
    #   Options FileInfo AuthConfig Limit                                      
    #                                                                          
    AllowOverride None

    #                                                                          
    # Controls who can get stuff from this server.                             
    #                                                                          
    Require all granted

    # use mod_rewrite for pretty URL support                                   
    RewriteEngine on

    # If a directory or a file exists, use the request directly                
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # Otherwise forward the request to index.php                               
    RewriteRule . index.php

</Directory>

```

Apache再起動する

```
[vagrant@localhost ~]$ sudo systemctl restart httpd
```

http://192.168.33.10/requiments.php にアクセスする。

成功！！
![Yii_Congratulations.png](https://qiita-image-store.s3.amazonaws.com/0/6311/8a522d12-9e78-8b27-343c-075d1ed35cce.png "Yii_Congratulations.png")


## 問題解決

### php-xmlが入っていないと叫ばれた

```
phpunit/phpunit 4.8.9 requires ext-dom * -> the requested PHP extension dom is missing from your 
```

上記のようなエラーが出た場合、DOM Extensionを入れる必要がある。

### php-XXX をインストールしてもインストールできない

いくら、yum install しても、yum list installed php-XXX で出てこない場合

そもそも、リポジトリがまずいことがある。

```
[vagrant@localhost ~]$ sudo yum -y install --enablerepo=remi,remi-php70 php php-devel php-mbstring php-pdo php-gd php-openssl php-xml
```

上記のように、remiリポジトリを指定している場合、

```
[vagrant@localhost ~]$ sudo yum -y install --enablerepo=remi,remi-php70 php-XXX
```

と指定しないとデフォルトのリポジトリを見に行くのでインストールされない。

参考：[CentOS6／CentOS7にPHP5.6／PHP7をyumでインストール](http://qiita.com/ozawan/items/caf6e7ddec7c6b31f01e)

### (13)Permission denied で 403 が発生して泣きそう

**アクセスするURL**
http://192.168.33.10/requiments.php

```ブラウザ
403 Forbidden
You don't have permission to access /requiments.php on this server.
```

```エラーログ
[vagrant@localhost home]$ sudo cat  /etc/httpd/logs/error_log
[Tue Nov 22 05:59:54.132700 2016] [core:error] [pid 11037] (13)Permission denied: [client 192.168.33.1:49446] AH00035: access to /requiments.php denied (filesystem path '/home/vagrant/basic') because search permissions are missing on a component of the path
```

**Permission denied** なので、アクセス先の権限を変更する

```
[vagrant@localhost ~]$ cd ../
[vagrant@localhost home]$ ls
vagrant
[vagrant@localhost home]$ ll
合計 4
drwx------. 8 vagrant vagrant 4096 11月 22 07:26 vagrant
[vagrant@localhost home]$ sudo chmod 755 vagrant
[vagrant@localhost home]$ ll
合計 4
drwxr-xr-x. 8 vagrant vagrant 4096 11月 22 07:26 vagrant
```