Web Service

Nodejsの始め方

NodeJSは、サーバーサイドのWebアプリケーションを開発するためのオープンソースでクロスプラットフォームな実行環境です。今回は、NodeJSをNode Package Module(NPM)を使って、ステップバイステップで基本的な実装と解説を学びます。

NodeJSは、イベント駆動型のノンブロッキングI/Oモデルを採用しているため、軽量で効率的です。

NodeJSとNPMのインストールは、NodeJSの公式ホームページから入手できるインストーラーパッケージを使用することで簡単に行うことができます。

Nodejs

  • NodeJS WebSiteからインストーラーをダウンロードします。
  • インストーラーを実行します。
  • インストーラーの手順に従って、使用許諾契約に同意し、「次へ」ボタンをクリックします。
  • システム/マシンを再起動します。

以下のコマンドで、nodejsのバージョンを確認します。

node --version

コマンドでnpmのバージョンをテストします。

npm --version

test.js ファイルを作成します。

/*test.js file*/
console.log("Node is working");

test.jsは、コマンドプロンプトからNodeコマンド > node test.jsで実行することができます。これでインストールは終了です。

Node Package Module

NPMは、JavaScript開発者が効率的に依存関係をロードするのを助けるパッケージモジュールです。依存関係をロードするには、コマンドプロンプトでコマンドを実行する必要があります。

npm install

このコマンドは、ルートディレクトリにあるpackage.jsonという名前のjsonファイルを見つけて、そのファイルに定義されているすべての依存関係をインストールするものです。

Package.json

Package.jsonはこんな感じです。

{
  "name": "ApplicationName",
  "version": "0.0.1",
  "description": "Application Description",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/npm/npm.git"
  },
  "dependencies": {
    "express": "~3.0.1",
    "angular": "latest",
    "angular-ui-router": "~0.2.11",
  }
}

package.jsonで最も重要なのは、名前とバージョンです。これらは実際に必須であり、これがないとパッケージはインストールされません。

Repository

{
  "repository": {
    "type": "git",
    "url": "https://github.com/npm/npm.git"
  }
}

コードが存在する場所を指定します。もしgitリポジトリがGitHubでない場合は、npm docsコマンドで見つけることができます。

Scripts

{
 "scripts": {
    "start": "node server.js"
  }
}

NPMは、npm install、npm start、npm stopなど、便利なスクリプトを多数提供しています。

パッケージのルートにserver.jsファイルがある場合、npmはデフォルトでnode server.jsを開始コマンドとして使用します。

Dependencies

{
   "dependencies": {
     "express": "~3.0.1",
     "angular":"latest",
     "angular-ui-router": "~0.2.11",
  }
}

依存関係は、パッケージ名とバージョン範囲を対応させたシンプルなオブジェクトで指定します。

Example:

/*server.js*/

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer(function(req, res) {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, function() {
  console.log('Server running at http://'+ hostname + ':' + port + '/');
});

require(‘http’) を使って http サーバを作成し、それを http という変数に渡しています。ここでは、localHost(127.0.0.1)とポート番号3000を使用し、これをそれぞれ変数hostnameとportに代入しています。createServerメソッドを使用して、httpサーバーを作成します。

次に、server.jsファイルをnodeでコマンドを使って実行します。

node server

ブラウザを開き、URL http://127.0.0.1:3000/ を入力してください。ブラウザが画面にHello Worldのメッセージを表示します。

これで、サンプルのnodejsスクリプトを作成し、正常に実行できるようになりました。

By Tsuki



Vue.jsの実用的なヒント

開発時にトリックを使用できれば、開発はよりスマートになり、時間を短縮できます。この記事では、Vuejsの最高のトリックを共有するつもりです。

1つのcomponentを複数のルートで使用する

複数のルートが同じVue componentに解決されることは、開発者が遭遇するかなり一般的な状況です。

しかし、問題は、Vueがアプリを最適化し、新しいコンポーネントを作成する代わりに、既存のコンポーネントを再利用することです。そのため、同じコンポーネントを使用するルート間で切り替えようとしても、何も変わりません。

router.js

const routes = [
  {
    path: "/a",
    component: ArticleComponent,
  },
  {
    path: "/b",
    component: ArticleComponent,
  },
];

これを修正するには、要素に:keyプロパティを追加する必要があります。これはApp.vueファイルにある可能性があります。これは、ページが異なる場合に routerが認識するのに役立ちます。

App.vue

<router-view :key='$route.path' />

これで、アプリは既存のコンポーネントを再利用せず、ルートを切り替えるときにコンテンツを更新します。

小道具をタイプのリストに制限する

プロップ定義で「バリデーター」オプションを使用すると、プロップを特定の値のセットに制限できます。

export default {
  name: 'Image',
  props: {
    src: {
      type: String,
    },
    style: {
      type: String,
      validator: s => ['square', 'rounded'].includes(s)
    }
  }
};

この「validator」関数は小道具を受け取り、小道具が有効かどうかにかかわらず、trueまたはfalseのいずれかを返します。

single スコープスロットの省略形

スコープスロットはとても楽しいですが、それらを使用するには、多くの template タグも使用する必要があります。

幸いなことに、それを取り除くための速記がありますが、それは単一のスコープスロットを使用している場合に限られます。

<DataTable>
  <template #header="tableAttributes">
    <TableHeader v-bind="tableAttributes" />
  </template>
</DataTable>

次のように書き直すことができます。

<DataTable #header="tableAttributes">
  <TableHeader v-bind="tableAttributes" />
</DataTable>

シンプルでわかりやすく、すばらしい。

すべての小道具を子コンポーネントに渡す

小道具と言えば、親 componentからその子の1つにすべての小道具を渡す方法を知っておくと便利です。

簡単です。instanceのプロパティを覚えておく必要があります。

<child-comp v-bind="$props"></child-comp>

local スタイルと global スタイルを組み合わせる

通常、スタイルを操作するときは、スタイルを単一の component にスコープする必要があります。

<style scoped>
  .component {
    background: green;
  }
</style>

ただし、ピンチでは、スコープのないスタイルブロックを追加して、必要に応じてグローバルスタイルを追加することもできます。

<style>
  /* Applied globally */
  .component p {
    margin-bottom: 16px;
  }
</style>

<style scoped>
  /* Scoped to this specific component */
  .component {
    background: green;
  }
</style>

v-forでの破壊

v-forで分解できることをご存知ですか?

<li
  v-for="{ name, id } in users"
  :key="id"
>
  {{ name }}
</li>

次のようなタプルを使用することで、v-forからインデックスを取得できることがより広く知られています。

<li v-for="(movie, index) in [
  'Lion King',
  'Frozen',
  'The Princess Bride'
]">
  {{ index + 1 }} - {{ movie }}
</li>

オブジェクトを使用するときは、キーを取得することもできます。

<li v-for="(value, key) in {
  name: 'Lion King',
  released: 2019,
  director: 'Jon Favreau',
}">
  {{ key }}: {{ value }}
</li>

また、この2つの方法を組み合わせて、キーだけでなく、プロパティのインデックスも取得することが可能です。

<li v-for="(value, key, index) in {
  name: 'Lion King',
  released: 2019,
  director: 'Jon Favreau',
}">
  #{{ index + 1 }}. {{ key }}: {{ value }}
</li>

カスタムV-model

デフォルトでは、v-model は “@input” イベントリスナーと “:value” プロップに対する構文糖の機能です。実は、どのイベントと値のプロップを使うかを指定できることをご存知でしょうか?Vueコンポーネントにmodelプロパティを指定することで、簡単に指定することができます。

export default{
  model: {
     event: 'change',
     prop: 'checked'
  }
}

複数のv-ifを使用しないでください

条件付きで複数の要素をレンダリングする必要がある場合もありますが、多くの場合、次のようなものを記述します。

<div v-if="condition">content</div>
<div v-if="condition">content</div>
<div v-if="condition">content</div>

もっとエレガントに書けるから不要なんです。

<template v-if="condition">
  <div>content</div>
  <div>content</div>
  <div>content</div>
</template>

Arraysとobjectsを見る

ウォッチャーを使う上で一番厄介なのは、うまくトリガーできないことがあることです。

通常は、ArrayやObjectをウォッチしようとしているのに、deepをtrueに設定していないことが原因です。

export default {
  name: 'ColourChange',
  props: {
    colours: {
      type: Array,
      required: true,
    },
  },
  watch: {
    // Use the object syntax instead of just a method
    colours: {
      // This will let Vue know to look inside the array
      deep: true,

      // We have to move our method to a handler field
      handler()
        console.log('The list of colours has changed!');
      }
    }
  }
}

Vue 3の反応性APIを使用すると、次のようになります。

watch(
  colours,
  () => {
    console.log('The list of colours has changed!');
  },
  {
    deep: true,
  }
);

以上が、vuejsの開発における最高のトリックです。次回は、さらに多くのトリックを紹介する予定です。

By Tsuki



Laravel + Vue JS CRUD Single Page Applicationの作成

今回は、LaravelとVue JSを使ったSingle Page Applicationの作成方法についてご案内します。

ここでは、セットアップに必要な手順を説明します。

このコマンドでLaravelのプロジェクトを新規に作成する必要があります。

composer create-project laravel/laravel --prefer-dist laravel-vue

次に、プロジェクトの.env configファイルにデータベース名、ユーザー名、パスワードを追加して、データベース接続を行う必要があります。

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_vue
DB_USERNAME=root
DB_PASSWORD=

LaravelでArticleモデルを作成するには、以下のコマンドを実行してください。

php artisan make:model Article -m

database/migrations/create_articles_table.php に以下のコードを追加してください。

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateArticlesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('artcles', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('descriptions');            
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('articles');
    }
}

マイグレーションを呼び出すには、以下のコマンドを実行してください。

php artisan migrate

記事コントローラを作成

記事コントローラを作成し、CRUD操作のメソッドを定義する必要があります

php artisan make:controller ArticleController

Article Controllerを以下のコードで更新します。

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Article;
class ArticleController extends Controller
{
    public function index()
    {
        $articles = Article::all()->toArray();
        return array_reverse($articles);      
    }
    public function store(Request $request)
    {
        $article = new Article();
        $article->title = $request->input('title');
        $article->description = $request->input('description');
        $article->save();

        return response()->json('New Article is successfully created!');
    }
    public function show($id)
    {
        $article = Article::find($id);
        return response()->json($article);
    }
    public function update($id, Request $request)
    {
        $article = Article::find($id);
        $article->title= $request->title;
        $article->description = $request->description;
        $article->save();

        return response()->json('Article is successfully updated!');
    }
    public function destroy($id)
    {
        $article = Article::find($id);
        $article->delete();
        return response()->json('Article is successfully deleted!');
    }
}

routesのweb.phpとapi.phpを更新してください。

routes/web.php

<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
*/
 
Route::get('{any}', function () {
    return view('app');
})->where('any', '.*');

routes/api.php

<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ArticleController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
*/
Route::middleware('api')->group(function () {
    Route::resource('articles', ArticleController::class);
});

laravel/ui composer パッケージをインストールします。

composer require laravel/ui

次に、Vueの足場を設定します。

laravel/uiパッケージには、Vueを使い始めるために必要なすべてのものを自動的に足場にしてくれる便利なArtisanコマンドがいくつか用意されています。

php artisan ui vue

ファイルをコンパイルする

最後に、新しく追加された依存関係をインストールして、コンパイルする必要があります。

npm install && npm run dev

コマンドを使用して、vue router および vue axios パッケージをインストールします。

npm install vue-router vue-axios

次に、npm パッケージをインストールし、アセットをコンパイルするために、次のコマンドを実行します。

npm install
npm run watch

LaravelでVueを開始する

layoutフォルダを作成し、このフォルダ内にapp.blade.phpを作成してアプリケーションを設定する必要があります。

resources/views/layout/app.blade.php

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" value="{{ csrf_token() }}" />
    <title>Vue JS CRUD Operations in Laravel</title>
    <link href="{{ mix('css/app.css') }}" type="text/css" rel="stylesheet" />
</head>
<body>
    <div id="app"></div>
    <script src="{{ mix('js/app.js') }}" type="text/javascript"></script>
</body>
</html>

App.vue ファイルに router-view 命令を追加する必要があります。そこで、resources/js フォルダに App.js ファイルを作成します。

resources/js/App.js

<template>
    <div class="container"> 
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <div class="collapse navbar-collapse">
                <div class="navbar-nav">
                    <router-link to="/" class="nav-item nav-link">Articles List</router-link>
                    <router-link to="/create" class="nav-item nav-link">Create Article</router-link>
                </div>
            </div>
        </nav>
        <router-view> </router-view>
    </div>
</template>
 
<script>
    export default {}
</script>

そして、resources/js/componentsフォルダの中に必要なvue jsコンポーネントファイルを作成します。

resources/js/components/AllArticle.vue

<template>
    <div>
        <h2 class="text-center">Article List</h2>
 
        <table class="table">
            <thead>
            <tr>
                <th>ID</th>
                <th>Title</th>
                <th>Desciption</th>
                <!-- <th>Actions</th> -->
            </tr>
            </thead>
            <tbody>
            <tr v-for="article in articles" :key="a.article">
                <td>{{ article.id }}</td>
                <td>{{ article.title }}</td>
                <td>{{ article.description}}</td>
                <td>
                    <div class="btn-group" role="group">
                        <router-link :to="{name: 'edit', params: { id: article.id }}" class="btn btn-success">Edit</router-link>
                        <button class="btn btn-danger" @click="deleteArticle(article.id)">Delete</button>
                    </div>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</template>
 
<script>
    export default {
        data() {
            return {
                articles: []
            }
        },
        created() {
            this.axios
                .get('http://localhost:8000/api/articles/')
                .then(response => {
                    this.articles = response.data;
                });
        },
        methods: {
            deleteArticle(id) { 
                this.axios
                    .delete(`http://localhost:8000/api/articles/${id}`)
                    .then(response => {
                        let i = this.articles.map(data => data.id).indexOf(id);
                        this.articles.splice(i, 1)
                    });
            }
        }
    }
</script>

resources/js/components/CreateArticle.vue

<template>
    <div>
        <h3 class="text-center">Create Article</h3>
        <div class="row">
            <div class="col-md-6">
                <form @submit.prevent="addArticle">
                    <div class="form-group">
                        <label>Title</label>
                        <input type="text" class="form-control" v-model="article.title">
                    </div>
                    <div class="form-group">
                        <label>Description</label>
                        <input type="text" class="form-control" v-model="article.description">
                    </div>
                    <button type="submit" class="btn btn-primary">Create</button>
                </form>
            </div>
        </div>
    </div>
</template>
 
<script>
    export default {
        data() {
            return {
                article: {}
            }
        },
        methods: {
            addArticle() {
                this.axios
                    .post('http://localhost:8000/api/articles', this.article)
                    .then(response => (
                        this.$router.push({ name: 'home' })
                    ))
                    .catch(err => console.log(err))
                    .finally(() => this.loading = false)
            }
        }
    }
</script>

 resources/js/components/EditArticle.vue

<template>
    <div>
        <h3 class="text-center">Edit Article</h3>
        <div class="row">
            <div class="col-md-6">
                <form @submit.prevent="updateArticle">
                    <div class="form-group">
                        <label>Title</label>
                        <input type="text" class="form-control" v-model="article.title">
                    </div>
                    <div class="form-group">
                        <label>Detail</label>
                        <input type="text" class="form-control" v-model="article.description">
                    </div>
                    <button type="submit" class="btn btn-primary">Update</button>
                </form>
            </div>
        </div>
    </div>
</template>
 
<script>
    export default {
        data() {
            return {
                article: {}
            }
        },
        created() {
            this.axios
                .get(`http://localhost:8000/api/articles/${this.$route.params.id}`)
                .then((res) => {
                    this.article = res.data;
                });
        },
        methods: {
            updateArticle() {
                this.axios
                    .patch(`http://localhost:8000/api/articles/${this.$route.params.id}`, this.article)
                    .then((res) => {
                        this.$router.push({ name: 'home' });
                    });
            }
        }
    }
</script>

vueのルートを作成するには、resources/jsディレクトリの中にroutes.jsを作成します。

resources/js/routes.js

import AllArticle from './components/AllArticle.vue';
import CreateArticle from './components/CreateArticle.vue';
import EditArticle from './components/EditArticle.vue';
 
export const routes = [
    {
        name: 'home',
        path: '/',
        component: AllArticle
    },
    {
        name: 'create',
        path: '/create',
        component: CreateArticle
    },
    {
        name: 'edit',
        path: '/edit/:id',
        component: EditArticle
    }
];

最後にVue App.jsを定義します。

 resources/js/app.js

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */
require('./bootstrap');
window.Vue = require('vue');
import App from './App.vue';
import VueAxios from 'vue-axios';
import VueRouter from 'vue-router';
import axios from 'axios';
import { routes } from './routes';
/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */
Vue.use(VueRouter);
Vue.use(VueAxios, axios);
 
const router = new VueRouter({
    mode: 'history',
    routes: routes
});
 
const app = new Vue({
    el: '#app',
    router: router,
    render: h => h(App),
});

アプリを起動するには、以下の2つのコマンドを実行します。

npm run watch
php artisan serve

ブラウザで http://127.0.0.1:8000 にアクセスすると、記事の一覧表示、記事の作成、更新ができます。

この記事があなたのお役に立てれば幸いです。

By Tsuki



Awesome features of PHP 8

PHP 8 has been officially released for general users. PHP 8 brings a host of new features improvements, functions, and deprecations to the language compared to PHP 7. Among all of these new features, the JIT compiler is the one sharing the limelight. However, other features like syntax changes are also to be taken into account as it is these features that will have a greater impact on the practitioners.

New features include:

  • Named arguments
  • Union types
  • Constructor property promotion
  • Custom object serialization
  • Match expression
  • Nullsafe operator
  • Improvements in the type system and error handling

New PHP Functions

  • New str_contains() function
  • New str_starts_with() and str_ends_with() functions
  • New fdiv() function
  • get_debug_type() function

str_contains()

Helps us in determining whether the given sub-string is present inside the string.

Example :

str_contains ( string $austin , string $tin ) : bool

Executes a case-sensitive operations and checks whether the string austin contains the substring tin.

 — string_starts_with and str_ends_with()

Using this function we can easily find whether the given sub-string is at the beginning or ending of the string.

Example:

str_starts_with(string $austin, string $au): bool;

str_ends_with(string $austin, string $tin): bool;

These new functions can be impersonated with strpossubstrstrncmp, and substr_compare. However, the new functions were favourably received due to its engine-level optimizations and their regular use cases.

fdiv()

The new fdiv() function has similar ability as the fmod() and intdiv() functions, that allows for division by 0. Instead of getting errors, you’ll get INF, -INF, or NAN, depending on the scenario.

get_debug_type()

The new get_debug_type function always returns the true native type of variables. It returns a return native type names, e.g., int rather than integer, double instead of float.

get_debug_type() function helps in

  • Error reporting
  • Debugging
  • Business logic
  • By Tsuki



    Advantages of Laragon

    Laragon is a program that provides the WAMP environment (which stands for Windows, Apache, MySQL and PHP) and can completely replace XAMPP which has many current bugs. With Laragon, we can easily, quickly and conveniently set up the WAMP environment and manage them in local environment.

    In addition to supporting PHP and MySQL, Laragon also supports other web programming languages ​​such as Node.js, Python, Java, Go, Ruby and other database management systems like PostgreSQL, MongoDB. This software suite is extremely popular in the Laravel community, downloaded and loved by thousands of programmers around the world.

    XAMPP and WAMP

    Before talking about Laragon, I would like to first go through my development web server history. First, I always used Windows-based computers for all my development work. When I was starting, the only viable solutions for Windows development was to set everything manually or to use XAMPP or WAMP server software. For a while, I used WAMP, but for the most part, XAMPP was my preferred environment. And I had different versions of XAMPP installed until recently, each one with varying versions of PHP.

    Laragon will allow switch between PHP versions, using Apache and Nginx, and maybe having support for different MySQL versions. Laragon is not easy to use as Local, but once we set it up, it is working as we expect it to. Most operations are done via the context menu for the application sitting in the taskbar notifications area.

    The following are the benefits of laragon.

    — PHP version support

    — CMDER terminal support

    — Laragon provides us a strong database management system with HeidiSql, optionally you can change it for phpmyadmin

    — SSL activation

    — Choosing Apache, Nginx for your web server

    — Activating Memcache, Redis

    — Quick app creating with GUI application

    — Changing ports very quickly and easily

    — Sharing your local site for the public with Ngrok on laragon

    — Email management

    — Powerful universal development environment for PHP, Node.js, Python, Java, Go, Ruby. It is fast, lightweight, easy-to-use and easy-to-extend

    By Tsuki




    アプリ関連ニュース

    お問い合わせはこちら

    お問い合わせ・ご相談はお電話、またはお問い合わせフォームよりお受け付けいたしております。

    tel. 06-6454-8833(平日 10:00~17:00)

    お問い合わせフォーム