LaravelのHomesteadでVagrantデビューした話
はじめに
先日の記事では、VirtualBoxにCentOS7のイメージを入れて、Laravelの開発環境を準備しました。
しかし、Laravelの公式サイトでは「Homestead」という環境もあるよと教えてくれています。
これを今回は導入してみようと思います。
そもそもHomesteadとはなにか
Laravel Homestead is an official, pre-packaged Vagrant box that provides you a wonderful development environment without requiring you to install PHP, a web server, and any other server software on your local machine.
Laravel Homestead(入植農地、「ホームステード」)はパッケージを事前に済ませた、Laravel公式の"box"で、PHPやWebサーバ、その他のサーバソフトウェアをローカルマシンにインストールする必要なく、素晴らしい開発環境を準備できます。
公式サイトの文言を借りるとこんな感じ。
Vagrantで提供している環境のひとつですね。
いざ導入
仮想化ソフトのインストール(必要なら)
Before launching your Homestead environment, you must install VirtualBox, VMWare, Parallels or Hyper-V as well as Vagrant.
Homestead環境を起動する前にVagrantと共に、VirtualBoxか、VMWare、Parallels、Hyper-Vをインストールする必要があります。
Windows 10 Pro だとHyper-Vが使えるのですが、私のPCはHomeなので、VirtualBoxを使いました。
どのソフトを利用しても、Vagrantがラップしてくれる関係で、あまり意識することはないと思います。
ここのインストールについては省略します。
Vagrantのインストール
私の場合は、Windowsの64bit版をインストールしました。
msiファイルが229MBありました。
インストールするにあたって、基本的には「Next」で進めていくだけなので、ここも省略します。
Homestead Vagrant Boxのインストール
ここからはコマンドでの操作になります。
Powershellでコマンド実行が可能ですが、私はいつも使っているCygwinで実行しました。
実行コマンドに差異はないはず。
公式のドキュメントにある通り、コマンドを実行していきます。
vagrant box add laravel/homestead
==> box: Loading metadata for box 'laravel/homestead' box: URL: https://vagrantcloud.com/laravel/homestead 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) hyperv 2) parallels 3) virtualbox 4) vmware_desktop Enter your choice: 3
プロバイダーと書いてありますが、ここで利用する仮想化ソフトを選択します。
私の場合はVirtualBoxなので、「3」です。
Enter your choice: 3 ==> box: Adding box 'laravel/homestead' (v7.1.0) for provider: virtualbox box: Downloading: https://vagrantcloud.com/laravel/boxes/homestead/versions/7.1.0/providers/virtualbox.box box: Download redirected to host: vagrantcloud-files-production.s3.amazonaws.com box: Progress: 100% (Rate: 2568k/s, Estimated time remaining: --:--:--) ==> box: Successfully added box 'laravel/homestead' (v7.1.0) for 'virtualbox'!
「Successfully」とのことで無事成功のようです。
Homesteadのインストール
いよいよHomesteadのインストールです。
homeディレクトリにHomesteadディレクトリを作成することになります。
最初に言い忘れていましたが、Gitが必要になります。
$ git clone https://github.com/laravel/homestead.git ~/Homestead Cloning into '/home/${USER}/Homestead'... remote: Enumerating objects: 3314, done. remote: Total 3314 (delta 0), reused 0 (delta 0), pack-reused 3314 Receiving objects: 100% (3314/3314), 703.94 KiB | 1.02 MiB/s, done. Resolving deltas: 100% (2004/2004), done.
masterブランチは安定しているわけではないので、特定のブランチをcheckoutすることを推奨されています。
GitHubのサイトを見に行きましょう。
私の場合は最新の「v8.2.0」を指定しました。
$ cd Homestead/ ~/Homestead$ ~/Homestead$ git checkout -b v8.2.0
次に、Homestead.yamlという設定ファイルを生成するために、下記コマンドを実行します。
Mac/Linux と Windows とで違うところですね。
// Mac / Linux... bash init.sh // Windows... init.bat
私はLinux組なので、init.shを実行。
$ bash init.sh Homestead initialized!
Homesteadの設定
設定ファイルの初期値は下記のとおりです。
$ cat Homestead.yaml --- ip: "192.168.10.10" memory: 2048 cpus: 1 provider: virtualbox authorize: ~/.ssh/id_rsa.pub keys: - ~/.ssh/id_rsa folders: - map: ~/code to: /home/vagrant/code sites: - map: homestead.test to: /home/vagrant/code/public databases: - homestead # ports: # - send: 50000 # to: 5000 # - send: 7777 # to: 777 # protocol: udp # blackfire: # - id: foo # token: bar # client-id: foo # client-token: bar # zray: # If you've already freely registered Z-Ray, you can place the token here. # - email: foo@bar.com # token: foo # Don't forget to ensure that you have 'zray: "true"' for your site.
慣れてきたらいろいろと変更が必要になると思いますが、まず動かしてみることを考えるのであれば、一旦このままでもいいと思います。
ただし、いくつかこの通りの設定になっているかどうかを確認しないといけませんが。
例えば。
provider: virtualbox
利用する仮想化ソフトは合っているか。
authorize: ~/.ssh/id_rsa.pub keys: - ~/.ssh/id_rsa
sites: - map: homestead.test to: /home/vagrant/code/public
http://homestead.test で仮想環境にアクセスするようにしているので、必要に応じてhostsファイルを書き換える必要があります。
Windowsの場合は"C:\Windows\System32\drivers\etc\hosts"にありますので、メモ帳を「管理者権限で実行」で実行した上で、ファイルを開いて下記を追加してください。
192.168.10.10 homestead.test
Vagrant Boxの実行
~/Homestead$ vagrant up
これで実行できます。あとはブラウザからアクセスしてみたいのですが…
http:// homestead.test http://192.168.10.10
↓
No input file specified.
と表示されるのではないでしょうか。
これは、Homestead.yaml に設定したドキュメントルートに、ファイルが存在しないために発生しています。
なので、例えば
# 仮想環境に接続 $ vagrant ssh vagrant@homestead:~$ mkdir -p /home/vagrant/code/public/ vagrant@homestead:~$ vim /home/vagrant/code/public/index.php <?php echo "Hello, Homestead!";
とディレクトリとファイルを作成してあげれば、
Hello, Homestead!
と、きちんと意図した動作をすることが確認できると思います。
コマンドの定義
どこからでも vagrant up コマンドを実行できるように、bash関数を作成しておくと便利です。
これもマニュアルにあることですが。
$ vim ~/.bash_profile function homestead() { ( cd ~/Homestead && vagrant $* ) }
Windowsの場合は、Homestead.bat ファイルを下記の中身で作成して、PATHにファイルの場所を指定すればOKとのこと。
@echo off set cwd=%cd% set homesteadVagrant=C:\Homestead cd /d %homesteadVagrant% && vagrant %* cd /d %cwd% set cwd= set homesteadVagrant=
こうすれば今後、例えば"homestead ssh"と打てば、どこのディレクトリにいても"vagrant ssh"が実行可能になります。
その他
開発に必要なファイルの場所やコマンドなど。
起動した仮想環境にsshで接続
先に登場させましたが、
vagrant ssh
で接続が可能です。
$ vagrant ssh Welcome to Ubuntu 18.04.1 LTS (GNU/Linux 4.15.0-45-generic x86_64) _ _ _ | | | | | | | |__ ___ _ __ ___ ___ ___| |_ ___ __ _ __| | | '_ \ / _ \| '_ ` _ \ / _ \/ __| __/ _ \/ _` |/ _` | | | | | (_) | | | | | | __/\__ \ || __/ (_| | (_| | |_| |_|\___/|_| |_| |_|\___||___/\__\___|\__,_|\__,_| * Homestead 8.0.0 released! PHP 7.3 is now the default! * Settler v7.0.0 released! Make sure you update * Need PHP 5.6 or 7.0? Homestead 7.x Settler 6.4.0 0 packages can be updated. 0 updates are security updates. Last login: Sun Mar 10 13:48:36 2019 from 10.0.2.2 vagrant@homestead:~$
user, group
vagrant@homestead:~$ id uid=1000(vagrant) gid=1000(vagrant) groups=1000(vagrant),4(adm),24(cdrom),27(sudo),30(dip),33(www-data),46(plugdev),108(lxd),113(lpadmin),114(sambashare)
nginx
vagrant@homestead:~$ ls -l /var/log/nginx/ total 4 -rw-r----- 1 www-data adm 0 Feb 4 23:16 access.log -rw-r----- 1 www-data adm 0 Feb 4 23:16 error.log -rw-r--r-- 1 root root 3586 Mar 10 13:11 homestead.test-error.log
上記の
No input file specified.
の件も、ここのログを見ると書いてあります。
MySQL
vagrant@homestead:~$ mysql -uroot Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 3 Server version: 5.7.25-0ubuntu0.18.04.2 (Ubuntu) Copyright (c) 2000, 2019, 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> mysql> SELECT user, host FROM mysql.user; +------------------+-----------+ | user | host | +------------------+-----------+ | homestead | % | | homestead | 0.0.0.0 | | root | 0.0.0.0 | | debian-sys-maint | localhost | | mysql.session | localhost | | mysql.sys | localhost | | root | localhost | +------------------+-----------+ 7 rows in set (0.00 sec)
まだあると思うので、別途追記します。
最後に
まだ本当に下準備だけなので、これからLaravelプロジェクトを載せたりする必要があります。
とはいえ、上記の設定だけですでにここまでの準備が済むのはとっても便利です。
今後、積極的に使っていきたいと思います。
以上でした!
GAS (Google Apps Script) でファイル出力を行う
はじめに
小ネタです。
GAS (Google Apps Script) で文字コードを指定しつつ、ファイル出力することを考えます。
コード
/** * ファイル書き出し * @param {string} fileName ファイル名 * @param {string} content ファイルの内容 */ function createFile(fileName, content) { var folder = DriveApp.getFolderById('##### フォルダID #####'); var contentType = 'text/plain'; var charset = 'utf-8'; // Blob を作成する var blob = Utilities.newBlob('', contentType, fileName) .setDataFromString(content, charset); // ファイルに保存 folder.createFile(blob); }
解説
使い方
フォルダID、ContentType、文字コードを指定するだけでOKです。
下記URLの******の部分がフォルダIDです。
https://drive.google.com/drive/u/0/folders/******
Blob ?
本当は createFile(name, content, mimeType)
というズバリなものもあるのですが、こちらは文字コードの指定ができません。
Class DriveApp | Apps Script | Google Developers
遠回りなようですが、Blobオブジェクトを生成して、setDataFromString(string, charset)
でファイルの内容を文字コード指定でセットしております。
Class Blob | Apps Script | Google Developers
最後に
JavaScriptの知識だけでは対応できないことも多いので、今後も小さいネタでも投下していこうと思います。
以上でした!
Laravelフレームワークの下準備をVirtualBox + CentOS7で行う
はじめに
Laravelを初めて使ってみることにしました。一番選ばれている印象が勝手にあります。
時間が許せばPhalconも使ってみる予定です。
ちなみに、私はSymfonyばかり使ってきた人間です。
バージョンはLTS(Long Term Support)の5.5を採用します。
5.5のドキュメントのGetting Startedに従って進めていきます。
https://laravel.com/docs/5.5/installation
手順
前提条件
必要なPHPの機能として、下記が要求されています。
Homesteadを使えば別なのですが、今回は使いません。
However, if you are not using Homestead, you will need to make sure your server meets the following requirements: PHP >= 7.0.0 OpenSSL PHP Extension PDO PHP Extension Mbstring PHP Extension Tokenizer PHP Extension XML PHP Extension
現在のモジュールを見たい場合は、下記のどちらかのコマンドでみることができます。
$ php -m $ php --modules
それと、Composerを使うことになるので、ない場合はインストールしましょう。 hrroct.hatenablog.com
Laravelのインストール
参照元に書いてあるとおりですが、下記を実行します。
$ composer global require "laravel/installer"
エラーが出たら随時対応しましょう。
私の場合はPHP extensionのzipがないよと言われました。
Problem 1 - laravel/installer v2.0.1 requires ext-zip * -> the requested PHP extension zip is missing from your system. - laravel/installer v2.0.0 requires ext-zip * -> the requested PHP extension zip is missing from your system. - Installation request for laravel/installer ^2.0 -> satisfiable by laravel/installer[v2.0.0, v2.0.1].
これは普通にyumでインストール可能です。
$ sudo yum install php-zip
私の場合は、PHP7をremiレポジトリを使って入れたので、指定が必要でしたが。
$ sudo yum install --enablerepo=remi,remi-php70 php-zip
改めて実行すると、成功のようでした。
$ composer global require "laravel/installer" Changed current directory to /home/${USER}/.config/composer Using version ^2.0 for laravel/installer ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Nothing to install or update Generating autoload files
そして指定通り、PATHを通しておきます。
$ vim /home/${USER}/.bash_profile export PATH=$PATH:$HOME/.config/composer/vendor/bin
ここでようやくインストールが完了です。
$ laravel --version
Laravel Installer 2.0.1
Laravelアプリケーションを作成する
パーミッションの関係もあって、rootで下記を実行してみたのですが。
# pwd /var/www/html # laravel new blog
Laravel 5.5系を想定していましたが、5.7系で作成されようとしているようで、エラーが頻発しました。
そこでもう一つの方法でインストールすることに。
composer create-project --prefer-dist laravel/laravel blog "5.5.*"
こちらならバージョンが指定できますし、問題なく成功しました。
ログは長いので省略で…。
php artisan serve
でサーバーを立てることが可能ですが、私の場合は仮想サーバーに立てたApache経由でアクセスさせることに。
そして下記にアクセス。
http://localhost:8080/blog/public/index.php
(私の場合は8080->80になるようポートフォワーディング設定をしております)
※ポートフォワーディングの設定についてはこちらをどうぞ。
hrroct.hatenablog.com
blog/public/.htaccessがきちんと動いていれば、index.phpはつけなくともアクセスできます。
http://localhost:8080/blog/public/
画面左上にこんなエラーが出ていたので、
The stream or file "/var/www/html/blog/storage/logs/laravel.log" could not be opened: failed to open stream: Permission denied
file_put_contents(/var/www/html/blog/storage/framework/sessions/tEHcnx2EJlGPRhLX4dH1zzrxxs3YXlWTVFY6NTHi): failed to open stream: Permission denied
file_put_contents(/var/www/html/blog/storage/framework/views/e96dfdf9e620607c1c331f2ec0b144a5937ac771.php): failed to open stream: Permission denied
それぞれこんなコマンドで対応。
# chmod 777 /var/www/html/blog/storage/logs/ # chmod 777 /var/www/html/blog/storage/framework/sessions/ # chmod 777 /var/www/html/blog/storage/framework/views/
SELinux関連の可能性もあります。
切り分けのために、下記コマンドで一時的に無効化してみるといいと思います。
setenforce 0
完了
こんな超絶シンプル画面が表示されます。
背景が現在白なので全然境目がわからなさそう…。
最後に
この先はLaravelの自体の話になるので、また別の機会に回します。
以上でした!
CentOS 7にComposerをインストール
はじめに
CentOS 7にcomposerをインストールします。 getcomposer.org
"Dependency Manager for PHP" とある通り、PHPをインストールしていることが前提です。
また、私はVirtualBox上のCentOS 7に対して実行します。が、直インストールされている場合と大差ないと思われます。
手順
公式サイトにあるとおりに実行していきます。
まずはダウンロードから。
特にインストール場所やバージョンを指定しないなから、書いてある通りです。
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" php -r "if (hash_file('sha384', 'composer-setup.php') === '93b54496392c062774670ac18b134c3b3a95e5a5e5c8f1a9f115f203b75bf9a129d5daa8ba6a13e2cc8a1da0806388a8') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" php composer-setup.php php -r "unlink('composer-setup.php');"
実行ファイルなのでbin配下に移動しておきます。
ユーザーによるインストールなので、/usr/local/bin/へ。
# mv composer.phar /usr/local/bin/composer # composer --version Composer version 1.8.0 2018-12-03 10:31:16
最後に
あっさり終わってしまったので、これにておしまいです。 以上でした!
Wikipediaのデータからプレーンテキストを出力
はじめに
Wikipediaのデータを出力する方法はいろいろあります。
その中のひとつ、Wikipedia Extractorを試してみました。
Wikipedia Extractor - Medialab
やり方
データはここから取得しました。
Index of /jawiki/latest/
jawiki-latest-pages-articles.xml.bz2
そして、データのあるディレクトリにPythonファイルをダウンロード。
$ curl -O http://medialab.di.unipi.it/Project/SemaWiki/Tools/WikiExtractor.py
バージョンを確認。
$ python WikiExtractor.py --version
WikiExtractor.py 2.55
オプションは公式ページにある通りです。
-h, --help show this help message and exit -o OUTPUT, --output OUTPUT output directory -b n[KM], --bytes n[KM] put specified bytes per output file (default is 1M) -B BASE, --base BASE base URL for the Wikipedia pages -c, --compress compress output files using bzip -l, --links preserve links -ns ns1,ns2, --namespaces ns1,ns2 accepted namespaces -q, --quiet suppress reporting progress info -s, --sections preserve sections -a, --article analyze a file containing a single article --templates TEMPLATES use or create file containing templates -v, --version print program version
引用元: http://medialab.di.unipi.it/wiki/Wikipedia_Extractor
私は下記の通りに実行しました。
$ python WikiExtractor.py --output ./text --bytes 500K jawiki-latest-pages-articles.xml
こんなディレクトリ構成になります。
$ ls -alR text/ text/: 合計 4 drwxrwxr-x. 3 user group 16 12月 30 20:27 . drwxr-xr-x. 3 user group 111 12月 30 21:11 .. drwxrwxr-x. 2 user group 4096 12月 30 21:11 AA text/AA: 合計 19764 drwxrwxr-x. 2 user group 4096 12月 30 21:11 . drwxrwxr-x. 3 user group 16 12月 30 20:27 .. -rw-rw-r--. 1 user group 500699 12月 30 21:08 wiki_00 -rw-rw-r--. 1 user group 489585 12月 30 21:08 wiki_01 -rw-rw-r--. 1 user group 510798 12月 30 21:08 wiki_02
内容はこんな感じ。docタグに囲まれて1記事が出力されています。
url属性にあるURLが元記事のURLなのですが、h2タグに当たる部分が省かれていることがわかります。
<doc id="56" url="https://ja.wikipedia.org/wiki?curid=56" title="地理"> 地理 地理(ちり、英: Geography) 「地理」という表現は古くからあり、有名なところでは漢書の『地理志』がある。 地理学とは、地球の表面と住民の状態、その相互関係を研究する学問である。 「地理」は、日本の学校で設置されている、「人間の生活に影響を与える地域的、社会的な構造」を学ぶための科目である。自然環境や産業環境などを含む環境を学習対象としている。小学校および中学校においては、歴史や公民と並び、社会科の一分野である。高等学校においては、最近は「地理歴史科」という教科の中の一科目となっており、「地理A」「地理B」に細分されている。 </doc>
気になる点
私はヘッダタグ部分もほしかったので、ちょっと残念。
そして、私の環境では、なぜか処理が途中で中断してしまいます。
食わせるファイルのサイズが大きかったからでしょうか。
$ python WikiExtractor.py --output ./text --bytes 500K jawiki-latest-pages-articles.xml INFO: Loaded 0 templates in 0.0s INFO: Starting page extraction from jawiki-latest-pages-articles.xml. INFO: Using 1 extract processes. zsh: killed python WikiExtractor.py --output ./text --bytes 500K
さいごに
なかなか自分がほしい形式で出力してくれるものが見つかりませんね。
自分で作るのが一番なのかも…と思いました。
以上でした!