アプリ関連ニュース

知っておいていただきたいこと – 1

今回は、知っておいた方がいいとおもったことをいくつか紹介します。

Tip – 1

APIやajaxリクエストのレスポンスとしてデータを返したくない場合は、簡単にnoContent()メソッドを使用することができます。非常にクリーンで、データなしの成功レスポンスを返すのに非常に便利です。

#HTTP, #PHP

public function update(){
  return response()->noContent();
}

Tip – 2

Laravel 9.xで新しい追加こと 「whenTableHasColumnwhenTableDoesntHaveColumn

この関数は、移行時にテーブルのカラムの更新を行うためのこと

//マイグレーション.アップ
 Schema::whenTableDoesntHaveColumn('product', 'order', function (Blueprint $table) {
            $table->unsignedInteger('order')->default(0);
        });

 //マイグレーション.ダウン
        Schema::whenTableHasColumn('product', 'order', function (Blueprint $table) {
            $table->dropColumn('order');
        });

ということで、今回はこれで終わります。

金担当 – Ami



Laravelでよりクリーンなコードを書く

行を正しく分割する

行は適当に分けないが、長くしすぎないようにする。配列を[]で開き、値をインデントするとうまくいく傾向がある。長い関数のパラメータ値も同様です。他にも、連鎖した呼び出しやクロージャも行を分割するのに適しています。

Bad
// No line split
return $this->request->session()->get($this->config->get('analytics.campaign_session_key'));

// Meaningless line split
return $this->request
  ->session()->get($this->config->get('analytics.campaign_session_key'));
// Good
return $this->request->session()->get(
  $this->config->get('analytics.campaign_session_key')
);

// Closure
new EventCollection($this->events->map(function (Event $event) {
  return new Entries\Event($event->code, $event->pivot->data);
}));

// Array
$this->validate($request, [
  'code' => 'string|required',
  'name' => 'string|required',
]);

ルックアップテーブルを使用する

else if ]ステートメントを繰り返し書く代わりに、配列を使って、持っているキーに基づいて、欲しい値を探します。コードはよりすっきりして読みやすくなり、何か問題が発生したときには理解しやすい例外を見ることができます。中途半端なエッジケースはありません。

// Bad
if ($order->product->option->type === 'pdf') {
    $type = 'book';
} else if ($order->product->option->type === 'epub') {
    $type = 'book';
} else if ($order->product->option->type === 'license') {
    $type = 'license';
} else if ($order->product->option->type === 'artwork') {
    $type = 'creative';
} else if $order->product->option->type === 'song') {
    $type = 'creative';
} else if ($order->product->option->type === 'physical') {
    $type = 'physical';
}

if ($type === 'book') {
    $downloadable = true;
} else if ($type === 'license') {
    $downloadable = true;
} else if $type === 'creative') {
    $downloadable = true;
} else if ($type === 'physical') {
    $downloadable = false;
}
// Good
$type = [
    'pdf'      => 'book',
    'epub'     => 'book',
    'license'  => 'license',
    'artwork'  => 'creative',
    'song'     => 'creative',
    'physical' => 'physical',
][$order->product->option->type];

$downloadable = [
    'book'     => true,
    'license'  => true,
    'creative' => true,
    'physical' => false,
][$type];

可読性を向上させる場合は変数を作成する

複雑な呼び出しから値が得られることもあり、そのような場合は変数を作成すると可読性が向上し、コメントの必要性がなくなります。文脈が重要であり、最終的な目標は読みやすさであることを忘れないでください。

// Bad
Visit::create([
  'url' => $visit->url,
  'referer' => $visit->referer,
  'user_id' => $visit->userId,
  'ip' => $visit->ip,
  'timestamp' => $visit->timestamp,
])->conversion_goals()->attach($conversionData);
// Good
$visit = Visit::create([
  'url'       => $visit->url,
  'referer'   => $visit->referer,
  'user_id'   => $visit->userId,
  'ip'        => $visit->ip,
  'timestamp' => $visit->timestamp,
]);

$visit->conversion_goals()->attach($conversionData);

アクションクラスの作成

一つのアクションのためにクラスを作ることで、物事がきれいになることもあります。モデルは、それに関連するビジネスロジックをカプセル化する必要がありますが、あまり大きくなりすぎるのもよくありません。

// Bad
public function createInvoice(): Invoice
{
  if ($this->invoice()->exists()) {
    throw new OrderAlreadyHasAnInvoice('Order already has an invoice.');
  }

  return DB::transaction(function () use ($order) {
    $invoice = $order->invoice()->create();

    $order->pushStatus(new AwaitingShipping);

    return $invoice;
  });
}
// Good
// Order model
public function createInvoice(): Invoice {
  if ($this->invoice()->exists()) {
    throw new OrderAlreadyHasAnInvoice('Order already has an invoice.');
  }

  return app(CreateInvoiceForOrder::class)($this);
}

// Action class
class CreatelnvoiceForOrder
{
  public function _invoke(Order $order): Invoice
  {
    return DB::transaction(function () use ($order) {
      $invoice = $order->invoice()->create();

      $order->pushStatus(new AwaitingShipping);

      return $invoice;
    });
  }
}

イベント利用

コントローラからイベントへのロジックのオフロードを検討します。例えば、モデルを作成するときです。この利点は、モデルの作成がどこでも(コントローラ、ジョブ、…)同じように動作し、コントローラはDBスキーマの詳細について心配する必要がなくなるということです。

// Bad
// Only works in this place & concerns it with
// details that the model should care about.
if (! isset($data['name'])) {
  $data['name'] = $data['code'];
}

$conversion = Conversion::create($data);
// Good
$conversion = Conversion::create($data);

// Model
class ConversionGoal extends Model
{
  public static function booted()
  {
    static::creating(function (self $model) {
      $model->name ??= $model->code;
    });
  }
}

来週は、クリーンコードに関するより多くのヒントを紹介する予定です。

By Tsuki



DataTablesを使用したテーブル生成とサーバーサイド連携(7)

本記事ではDataTablesを使用したテーブル生成方法とサーバーサイド連携方法をシェアします。
前回の記事でページング処理ができましたので、今回はデータテーブルの各項目にソート処理を追加していきたいと思います。

続きを読む

Basic HandTracking in Python, OpenCV using mediapipe

Today I would like to share about tracking hands in python and opencv using mediapipe library.

Let’s take a look.

OpenCV is a tool for image processing and performing computer vision tasks. It is an open-source library that can be used to perform tasks like face detection, objection tracking, landmark detection, and much more. It supports multiple languages including python, java C++.

MediaPipe is Google’s open-source framework for media processing. It is cross-platform that can run on Android, iOS, web.

First of all, we will import required libraries in line 1 to 3.

Next, in line 6, we need to create a VideoCapture Object to capture a video from a webcam.

And if not found camera, info message is displayed in line 9.

Then in line 14 to 16, we will call the methods of MediaPipe and create a Hands() object to detect handlandmarks.

Next, in line 21, while camera is opened, we will handle hand tracking processes .

In line 22 and 23, read the images from the camera and convert the images to RGB images because we will have to pass only RGB images in hands.process(imgRGB) of line 25.

In line 26, we can get hand Landmarks easily by the help of mediapipe. If we print landmarks, we will see they are coordinates in line 27.

And we need to draw every hand landmarks by using drawing_utils of mediapipe in line 29 to 31.

And we will also show the frame rate of the camera. So we will calculate fps with cTime(current time) and pTime(previous time) by using time library in line 33 and 35. Before that, firstly cTime and pTime are also needed to assign into 0 in line 18 and 19.

Then we will write fps value on the display capture in line 37.

Finally, in line 39 and 40, we output the live capture.

There we go.

So this is all for now. For further details information, here are the reference links.

https://docs.opencv.org/4.x/d6/d00/tutorial_py_root.html

https://google.github.io/mediapipe/getting_started/python.html

Hope you enjoy that.

By Asahi



Searching code snippets

Developers often spend hours searching for snippets to use and Google for StackOverflow on Sourcegraph. I will introduce to a website called snipt.dev , a search engine for codes you can reuse.

Code snippets are blocks of code that you can share and reuse. Reusing safe and tested code not only improves productivity, but also always imports the correct code for missing arguments (missing arguments, unchecked error codes, exceptions, etc.).

We usually don’t remember all the details for writing a block of code. If there are required or optional parameters, what parameters does the function take and what are their types? Code snippets allow you to use the code patterns directly to maximize your productivity.

snipt.dev is a code snippet search engine. You don’t have to google for hours. Find the snippet that’s right for you. For example, if you search for “react typescript”, snipt.dev will only show Snippets related to TypeScript, and “react javascript” will only show snippets related to JavaScript (and obviously react).

For example, if I want to search for array sorting code snippet for JavaScript,

I think this service is pretty convenient for developers like us. I hope this might be helpful for you too.

Yuuma



アプリ関連ニュース

お問い合わせはこちら

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

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

お問い合わせフォーム