投稿者: nori

  • サイト改装への道(18) 「MacでYii2+gulp」

    WindowsとMacで違うところはそれほどないが、自己満足のために書いておく。
    まず、yiiのルートフォルダに移動し、

    $ cd yii_advanced

    npmを初期化してpackage.jsonファイルを作る。

    $ npm initThis utility will walk you through creating a package.json file.It only covers the most common items, and tries to guess sane defaults.
    See `npm help json` for definitive documentation on these fieldsand exactly what they do.
    Use `npm install –save` afterwards to install a package andsave it as a dependency in the package.json file.
    Press ^C at any time to quit.name: (yii_advanced) version: (1.0.0) description: entry point: (index.js) test command: git repository: keywords: author: license: (ISC) About to write to yii_advanced/package.json:
    {  “name”: “yii_advanced”,  “version”: “1.0.0”,  “description”: “Yii 2 Advanced Project Template ===============================”,  “main”: “index.js”,  “directories”: {    “test”: “tests”  },  “scripts”: {    “test”: “echo “Error: no test specified” && exit 1″  },  “author”: “”,  “license”: “ISC”}

    Is this ok? (yes) yes

    gulpをローカルインストール。
    sudoを付けないとファイルの権限不足でエラーになる。

    $ sudo npm install –save-dev gulp
    gulp@3.9.0 ../../../node_modules/gulp
    ├── pretty-hrtime@1.0.0
    ├── interpret@0.6.2
    ├── deprecated@0.0.1
    ├── archy@1.0.0
    ├── minimist@1.1.1
    ├── v8flags@2.0.9 (user-home@1.1.1)
    ├── tildify@1.1.0 (os-homedir@1.0.0)
    ├── semver@4.3.6
    ├── chalk@1.0.0 (escape-string-regexp@1.0.3, ansi-styles@2.0.1, supports-color@1.3.1, strip-ansi@2.0.1, has-ansi@1.0.3)
    ├── orchestrator@0.3.7 (stream-consume@0.1.0, sequencify@0.0.7, end-of-stream@0.1.5)
    ├── liftoff@2.1.0 (extend@2.0.1, rechoir@0.6.1, flagged-respawn@0.3.1, resolve@1.1.6, findup-sync@0.2.1)
    ├── vinyl-fs@0.3.13 (graceful-fs@3.0.8, mkdirp@0.5.1, strip-bom@1.0.0, vinyl@0.4.6, defaults@1.0.2, through2@0.6.5, glob-stream@3.1.18, glob-watcher@0.0.6)
    └── gulp-util@3.0.6 (array-differ@1.0.0, array-uniq@1.0.2, lodash._reevaluate@3.0.0, lodash._reescape@3.0.0, lodash._reinterpolate@3.0.0, beeper@1.1.0, object-assign@3.0.0, replace-ext@0.0.1, vinyl@0.5.0, multipipe@0.1.2, lodash.template@3.6.1, through2@2.0.0, dateformat@1.0.11)

    バージョンチェック!

    $ gulp -v[5:48:18] CLI version 3.8.11[5:48:18] Local version 3.9.0

    あれ?バージョン違う。
    グローバルインストールができていない時や、バージョンが違う時は、

    $ sudo npm install -g gulp
    /usr/local/bin/gulp -> /usr/local/lib/node_modules/gulp/bin/gulp.jsgulp@3.9.0 /usr/local/lib/node_modules/gulp├── pretty-hrtime@1.0.0├── interpret@0.6.2├── deprecated@0.0.1├── archy@1.0.0├── minimist@1.1.1├── v8flags@2.0.9 (user-home@1.1.1)├── tildify@1.1.0 (os-homedir@1.0.0)├── chalk@1.0.0 (escape-string-regexp@1.0.3, ansi-styles@2.0.1, supports-color@1.3.1, strip-ansi@2.0.1, has-ansi@1.0.3)├── semver@4.3.6├── orchestrator@0.3.7 (stream-consume@0.1.0, sequencify@0.0.7, end-of-stream@0.1.5)├── gulp-util@3.0.6 (array-differ@1.0.0, array-uniq@1.0.2, lodash._reevaluate@3.0.0, lodash._reinterpolate@3.0.0, beeper@1.1.0, lodash._reescape@3.0.0, object-assign@3.0.0, replace-ext@0.0.1, vinyl@0.5.0, lodash.template@3.6.1, through2@2.0.0, multipipe@0.1.2, dateformat@1.0.11)├── vinyl-fs@0.3.13 (graceful-fs@3.0.8, strip-bom@1.0.0, defaults@1.0.2, vinyl@0.4.6, mkdirp@0.5.1, through2@0.6.5, glob-watcher@0.0.6, glob-stream@3.1.18)└── liftoff@2.1.0 (extend@2.0.1, rechoir@0.6.1, flagged-respawn@0.3.1, resolve@1.1.6, findup-sync@0.2.1)$ gulp -v[5:54:37] CLI version 3.9.0[5:54:37] Local version 3.9.0

    バージョンも一致!

    $ gulp
    [6:24:32] No gulpfile found

    それではgulpfile.jsを作りましょう。

    $vi gulpfile.jsvar gulp = require(‘gulp’);
    gulp.task(‘default’, function() {
    console.log(“Hello World!”);
    });

    で、

    $ gulp[6:27:04] Using gulpfile yii_advanced/gulpfile.js[6:27:04] Starting ‘default’…Hello World![6:27:04] Finished ‘default’ after 151 μs

    よし。
    あとは、Browsersyncをやりたいが、それはWindowsの時と一緒だから、もういいか。
  • サイト改装への道(17) 「Yii2にBrowserSyncを仕込む」

    いよいよ本題に近づいてきた。
    これを試したくて頑張ってきた。多分。

    まずは、BrowserSyncのインストール。

    $ npm install –save-dev browser-sync
    browser-sync@2.7.12 node_modulesbrowser-sync
    ├── async-each-series@0.1.1
    ├── query-string@2.3.0
    ├── longest@1.0.1
    ├── ucfirst@0.0.1
    ├── emitter-steward@0.0.1
    ├── opn@2.0.1
    ├── dev-ip@1.0.1
    ├── pad-left@1.0.2 (repeat-string@1.5.2)
    ├── ua-parser-js@0.7.7
    ├── portscanner@1.0.0 (async@0.1.15)
    ├── serve-static@1.10.0 (escape-html@1.0.2, parseurl@1.3.0, send@0.13.0)
    ├── foxy@11.0.3 (cookie@0.1.3, lodash.merge@3.3.1)
    ├── connect@3.4.0 (utils-merge@1.0.0, parseurl@1.3.0, debug@2.2.0, finalhandler@0.4.0)
    ├── browser-sync-client@2.2.1 (fresh@0.3.0, etag@1.7.0)
    ├── meow@3.3.0 (object-assign@3.0.0, camelcase-keys@1.0.0, minimist@1.1.1, indent-string@1.2.1)
    ├── immutable@3.7.4
    ├── resp-modifier@4.0.2 (minimatch@2.0.8)
    ├── anymatch@1.3.0 (arrify@1.0.0, micromatch@2.1.6)
    ├── chokidar@1.0.3 (arrify@1.0.0, is-glob@1.1.3, path-is-absolute@1.0.0, glob-parent@1.2.0, async-each@0.1.6, is-binary-path@1.0.1, readdirp@1.3.0)
    ├── serve-index@1.7.0 (escape-html@1.0.2, parseurl@1.3.0, batch@0.5.2, http-errors@1.3.1, debug@2.2.0, accepts@1.2.9, mime-types@2.1.1)
    ├── easy-extender@2.3.1 (lodash@2.4.2)
    ├── eazy-logger@2.1.2 (tfunk@3.0.1, opt-merger@1.1.0)
    ├── localtunnel@1.5.1 (debug@0.7.4, optimist@0.3.4, request@2.11.4)
    ├── socket.io@1.3.5 (debug@2.1.0, has-binary-data@0.1.3, socket.io-adapter@0.3.1, engine.io@1.5.1, socket.io-parser@2.2.4, socket.io-client@1.3.5)
    ├── lodash@3.9.3
    └── browser-sync-ui@0.5.11 (angular-touch@1.4.1, connect-history-api-fallback@0.0.5, angular-sanitize@1.4.1, angular-route@1.4.1, angular@1.4.1, stream-throttle@0.1.3, weinre@2.0.0-pre-I0Z7U9OV)
    そして、gulpfile.jsを編集。

    var gulp = require(‘gulp’);
    var browserSync = require(‘browser-sync’);
    var httpProxy = require(‘http-proxy’);
    gulp.task(‘browser-sync’, function() {
    var proxy = httpProxy.createProxyServer({});
    browserSync({
    notify : false,
    logPrefix : ‘WSK’,
    server : {
    baseDir : “./”,
    middleware : function(req, res, next) {
    var url = req.url;
    proxy.web(req, res, {
    target : ‘http://localhost:80’
    });
    }
    },
    startPath : “/yii2-app-advanced/frontend/web/index.php”,
    });
    });
    gulp.task(‘bs-reload’, function() {
    browserSync.reload();
    });
    gulp.task(‘default’, [ ‘browser-sync’ ], function() {
    gulp.watch(“frontend/**/*.html”, [ ‘bs-reload’ ]);
    gulp.watch(“frontend/**/*.php”, [ ‘bs-reload’ ]);
    });
    はい。いきなりなので訳分かりませんね。
    コメントを付けておきましょう。30分後の自分のために。

    var gulp = require(‘gulp’); // gulp本体のインスタンスを生成
    var browserSync = require(‘browser-sync’); // プラグインである「browser-sync」のインスタンスを生成
    var httpProxy = require(‘http-proxy’); // 同じくプラグインである「http-proxy」のインスタンスを生成
    // 1つ目のタスク「browser-sync」を定義する
    gulp.task(‘browser-sync’, function() { // 「browser-sync」を実行する指示があれば、function()を実行する。
    var proxy = httpProxy.createProxyServer({}); // Proxyサーバを生成
    browserSync({ // browser-syncの本体
    notify : false, // 画面右上にちらっと「Connected to BrowserSync」と表示したくない
    logPrefix : ‘WSK’, // ログの前に、[WSK]と表示させる。
    server : { // サーバーの設定
    baseDir : “./”, // 基本URL
    middleware : function(req, res, next) { // ミドルウェアの定義
    proxy.web(req, res, {
    target : ‘http://localhost:80’
    });
    //next(); // 次のミドルウェアを呼ぶ
    }
    },
    startPath : “/yii2-app-advanced/frontend/web/index.php”, // 最初に開くページ
    });
    });
    // 2つ目のタスク「bs-reload」を定義する
    gulp.task(‘bs-reload’, function() {
    browserSync.reload(); // リロード
    });
    // 3つ目のタスク「default」を定義する
    // コマンドラインで、引数なしのgulpを実行すると、このタスクが実行される。
    gulp.task(‘default’, [ ‘browser-sync’ ], function() { // タスク「browser-sync」を実行した後にfuncion()を実行する。
    gulp.watch(“frontend/**/*.html”, [ ‘bs-reload’ ]); // frontendフォルダ以下の全てのhtmlファイルを監視し、変更されたらタスク「bs-reload」を実行する。
    gulp.watch(“frontend/**/*.php”, [ ‘bs-reload’ ]); // frontendフォルダ以下の全てのphpファイルを監視し、変更されたらタスク「bs-reload」を実行する。
    });

    合ってるのか?間違ってるのか?
    でも、GitBashで、gulpと入力すれば、実際BrowserSyncが実現できたから、機能はしているみたい。
    さて、ここからどんだけ改善できるかだな。
  • サイト改装への道(16) 「npm installのオプション」

    $ npm install gulp
    昨日、そうやってgulpをローカルにインストールしました。

    だがしかし、nmpのインストールコマンドには、オプションがあります。

    –save-dev

    開発時にのみ必要なライブラリをインストールする際に指定する。

    –save

    実行環境で必要なライブラリをインストールする際に指定する。

    これらのオプションを付けておくと、package.jsonが変更され、nmp installだけで必要なパッケージをインストールしてくれるという仕組み。

    だが、packege.json自体を作る手順を踏んでないと働かないらしい。
    なので、まず初期化。

    $ npm init
    This utility will walk you through creating a package.json file.
    It only covers the most common items, and tries to guess sensible defaults.
    See `npm help json` for definitive documentation on these fields
    and exactly what they do.
    Use `npm install –save` afterwards to install a package and
    save it as a dependency in the package.json file.
    Press ^C at any time to quit.
    name: (yii2-app-advanced)
    version: (1.0.0)
    description:
    entry point: (gulpfile.js)
    test command:
    git repository:
    keywords:
    author:
    license: (ISC)
    About to write to d:xampphtdocsyii2-app-advancedpackage.json:
    {
      “name”: “yii2-app-advanced”,
      “version”: “1.0.0”,
      “description”: “Yii 2 Advanced Project Template ===============================”,
      “main”: “gulpfile.js”,
      “directories”: {
        “test”: “tests”
      },
      “scripts”: {
        “test”: “echo “Error: no test specified” && exit 1″
      },
      “author”: “”,
      “license”: “ISC”
    }

    Is this ok? (yes) yes
    最後のyesを入力した以外は、そのままEnterキー。
    この初期化で、次のようなファイルpackege.jsonが生成された。

    {
      “name”: “yii2-app-advanced”,
      “version”: “1.0.0”,
      “description”: “Yii 2 Advanced Project Template ===============================”,
      “main”: “gulpfile.js”,
      “directories”: {
        “test”: “tests”
      },
      “scripts”: {
        “test”: “echo “Error: no test specified” && exit 1″
      },
      “author”: “”,
      “license”: “ISC”
    }

    その後にgulpをsave-devでインストール。

    $ npm install –save-dev gulp
    npm WARN package.json yii2-app-advanced@1.0.0 No repository field.
    gulp@3.9.0 node_modulesgulp
    ├── interpret@0.6.2
    ├── pretty-hrtime@1.0.0
    ├── deprecated@0.0.1
    ├── archy@1.0.0
    ├── tildify@1.1.0 (os-homedir@1.0.0)
    ├── minimist@1.1.1
    ├── v8flags@2.0.7 (user-home@1.1.1)
    ├── chalk@1.0.0 (escape-string-regexp@1.0.3, ansi-styles@2.0.1, supports-color@1.3.1, has-ansi@1.0.3, strip-ansi@2.0.1)
    ├── semver@4.3.6
    ├── orchestrator@0.3.7 (stream-consume@0.1.0, sequencify@0.0.7, end-of-stream@0.1.5)
    ├── liftoff@2.1.0 (extend@2.0.1, rechoir@0.6.1, flagged-respawn@0.3.1, resolve@1.1.6, findup-sync@0.2.1)
    ├── vinyl-fs@0.3.13 (graceful-fs@3.0.8, strip-bom@1.0.0, defaults@1.0.2, vinyl@0.4.6, mkdirp@0.5.1, through2@0.6.5, glob-stream@3.1.18, glob-watcher@0.0.6)
    └── gulp-util@3.0.5 (array-differ@1.0.0, array-uniq@1.0.2, lodash._reinterpolate@3.0.0, beeper@1.1.0, lodash._reescape@3.0.0, object-assign@2.1.1, lodash._reevaluate@3.0.0, replace-ext@0.0.1, vinyl@0.4.6, lodash.template@3.6.1, through2@0.6.5, multipipe@0.1.2, dateformat@1.0.11)

    そうすると、packege.jsonは、次のように更新されている。

    {
      “name”: “yii2-app-advanced”,
      “version”: “1.0.0”,
      “description”: “Yii 2 Advanced Project Template ===============================”,
      “main”: “gulpfile.js”,
      “directories”: {
        “test”: “tests”
      },
      “scripts”: {
        “test”: “echo “Error: no test specified” && exit 1″
      },
      “author”: “”,
      “license”: “ISC”,
      “devDependencies”: {    “gulp”: “^3.9.0”  }}

    うん。増えた。
    これでnode_modulesを配らなくても、npm installで開発環境をインストールしてくれる。
    という事かなぁ???
  • サイト改装への道(15) 「WindowsでYii2+gulp」

    Yii2のテンプレートをインストールしたら、そこにgulpをインストールする。
    グローバルインストールは終わっているので、GitBashで確認。

    $ gulp -v
    [19:31:28] CLI version 3.9.0
    カレントフォルダをテンプレートのフォルダに変更。

    $ cd c:/xampp/htdocs/yii2-app-advanced
    ローカルインストールが終わってないと、次のようにエラーとなる。

    $ gulp
    [25:19:04] Local gulp not found in ***
    [25:19:04] Try running: npm install gulp
    そして、gulpをローカルインストール。

    $ npm install gulp
    gulp@3.9.0 node_modulesgulp
    ├── pretty-hrtime@1.0.0
    ├── interpret@0.6.2
    ├── deprecated@0.0.1
    ├── archy@1.0.0
    ├── minimist@1.1.1
    ├── v8flags@2.0.7 (user-home@1.1.1)
    ├── tildify@1.1.0 (os-homedir@1.0.0)
    ├── chalk@1.0.0 (ansi-styles@2.0.1, escape-string-regexp@1.0.3, supports-color@1.3.1, strip-ansi@2.0.1, has-ansi@1.0.3)
    ├── semver@4.3.6
    ├── orchestrator@0.3.7 (stream-consume@0.1.0, sequencify@0.0.7, end-of-stream@0.1.5)
    ├── liftoff@2.1.0 (extend@2.0.1, rechoir@0.6.1, flagged-respawn@0.3.1, resolve@1.1.6, findup-sync@0.2.1)
    ├── gulp-util@3.0.5 (array-differ@1.0.0, array-uniq@1.0.2, object-assign@2.1.1, lodash._reescape@3.0.0, beeper@1.1.0, lodash._reinterpolate@3.0.0, lodash._reevaluate@3.0.0, replace-ext@0.0.1, vinyl@0.4.6, lodash.template@3.6.1, through2@0.6.5, multipipe@0.1.2, dateformat@1.0.11)
    └── vinyl-fs@0.3.13 (graceful-fs@3.0.8, defaults@1.0.2, strip-bom@1.0.0, vinyl@0.4.6, mkdirp@0.5.1, through2@0.6.5, glob-stream@3.1.18, glob-watcher@0.0.6)
    さて、再度gulp起動!

    $ gulp
    [25:27:29] No gulpfile found
    そりゃあ、そうだ。
    以下の内容のファイルを、gulpfile.jsとして、yii2-app-advancedフォルダに作って、

    var gulp = require(‘gulp’);
    gulp.task(‘default’, function() {
    console.log(“Hello World!”);
    });
    再度、

    $ gulp
    [25:44:04] Using gulpfile c:xampphtdocsyii2-app-advancedgulpfile.js
    [25:44:04] Starting ‘default’…
    Hello World!
    [25:44:04] Finished ‘default’ after 2.62 ms
    よし!

    Browsersyncは、いつになったら?

  • サイト改装への道(14) 「Yii2のインストール Windows編」

    Windowsにgulpを入れてみたので、そのままyii2も入れてしまおう。

    GitBashを起動して、カレントディレクトリをxamppのhtdocsに移動。

    $ cd c:/xampp/htdocs
    そして、yii2の上級テンプレートを作成。

    $ composer create-project –prefer-dist yiisoft/yii2-app-advanced
    Installing yiisoft/yii2-app-advanced (2.0.4)
      – Installing yiisoft/yii2-app-advanced (2.0.4)
        Downloading: 100%
    Created project in C:xampphtdocsyii2-app-advanced
    Loading composer repositories with package information
    Installing dependencies (including require-dev)
      – Installing yiisoft/yii2-composer (2.0.3)
        Loading from cache
      – Installing ezyang/htmlpurifier (v4.6.0)
        Loading from cache
      – Installing cebe/markdown (1.1.0)
        Loading from cache
      – Installing bower-asset/jquery (2.1.4)
        Loading from cache
      – Installing bower-asset/jquery.inputmask (3.1.63)
        Loading from cache
      – Installing bower-asset/punycode (v1.3.2)
        Loading from cache
      – Installing bower-asset/yii2-pjax (v2.0.4)
        Loading from cache
      – Installing yiisoft/yii2 (2.0.4)
        Loading from cache
      – Installing swiftmailer/swiftmailer (v5.4.1)
        Loading from cache
      – Installing yiisoft/yii2-swiftmailer (2.0.4)
        Loading from cache
      – Installing yiisoft/yii2-codeception (2.0.4)
        Loading from cache
      – Installing bower-asset/bootstrap (v3.3.5)
        Downloading: 100%
      – Installing yiisoft/yii2-bootstrap (2.0.4)
        Loading from cache
      – Installing yiisoft/yii2-debug (2.0.4)
        Loading from cache
      – Installing bower-asset/typeahead.js (v0.10.5)
        Loading from cache
      – Installing phpspec/php-diff (v1.0.2)
        Loading from cache
      – Installing yiisoft/yii2-gii (2.0.4)
        Loading from cache
      – Installing fzaninotto/faker (v1.5.0)
        Loading from cache
      – Installing yiisoft/yii2-faker (2.0.3)
        Loading from cache
    fzaninotto/faker suggests installing ext-intl (*)
    Writing lock file
    Generating autoload files
    あれ、もう終わり?

    上級テンプレートなので、あとは初期化して、

    $ php yii2-app-advanced/initYii Application Initialization Tool v1.0
    Which environment do you want the application to be initialized in?
      [0] Development
      [1] Production
      Your choice [0-1, or “q” to quit] 0
      Initialize the application under ‘Development’ environment? [yes|no] yes
      Start initialization …
       generate backend/config/main-local.php
       generate backend/config/params-local.php
       generate backend/web/index-test.php
       generate backend/web/index.php
       generate common/config/main-local.php
       generate common/config/params-local.php
       generate console/config/main-local.php
       generate console/config/params-local.php
       generate frontend/config/main-local.php
       generate frontend/config/params-local.php
       generate frontend/web/index-test.php
       generate frontend/web/index.php
       generate yii
       generate cookie validation key in backend/config/main-local.php
       generate cookie validation key in frontend/config/main-local.php
          chmod 0777 backend/runtime
          chmod 0777 backend/web/assets
          chmod 0777 frontend/runtime
          chmod 0777 frontend/web/assets
          chmod 0755 yii
          chmod 0755 tests/codeception/bin/yii
      … initialization completed.
    ちなみに開発環境としての初期化ね。

    次に、MySQLデータベース上に、ユーザーとデータベースを作成し、次のファイルをユーザ名とデータベース名に合わせて編集。
    c:/xampp/htdocs/yii2-app-advanced/common/config/main-local.php

    return [
        ‘components’ => [
            ‘db’ => [
                ‘class’ => ‘yiidbConnection’,
                ‘dsn’ => ‘mysql:host=localhost;dbname=yii’,
                ‘username’ => ‘yii’,
                ‘password’ => ‘yii’,
                ‘charset’ => ‘utf8’,
            ],
            ‘mailer’ => [
                ‘class’ => ‘yiiswiftmailerMailer’,
                ‘viewPath’ => ‘@common/mail’,
                // send all mails to a file by default. You have to set
                // ‘useFileTransport’ to false and configure a transport
                // for the mailer to send real emails.
                ‘useFileTransport’ => true,
            ],
        ],
    ];

    データベースを初期化!

    $ php yii2-app-advanced/yii migrate
    Yii Migration Tool (based on Yii v2.0.4)
    Creating migration history table “migration”…Done.
    Total 1 new migration to be applied:
            m130524_201442_init
    Apply the above migration? (yes|no) [no]:yes
    *** applying m130524_201442_init
        > create table {{%user}} … done (time: 0.313s)
    *** applied m130524_201442_init (time: 0.348s)

    Migrated up successfully.

    さあ、上級の世界に。