アプリ関連ニュース

6 Tips for optimizing a laravel application

Today, I would like to share about some tips for optimizing a laravel application. Let’s take a look.

1. Cache routes, config and views

Caching speeds up your application. This is important when deploying a application to a production environment.

To cache your routes, you can use the following command:
php artisan route:cache

To clear the route cache, you can use the following command:
php artisan route:clear

To cache config, you can use the following command:

php artisan config:cache

To cache your views, you can use the following command:

php artisan view:cache

2. Remove unused services

You should remove unused services when the application grows. This can be done by removing the service from the config/app.php file.

3. Remove unused packages

To keep the app clean, you should remove unused packages from the application. This can be done by removing the package from the composer.json file or by running the following command:

composer remove package-name

4. Remove development dependencies

You should also remove development dependencies when deploying to production. This can be done by running the following command:

composer install –prefer-dist –no-dev -o

5. Composer Autoload Optimization

For your applications, you should use the composer autoload optimization feature as the autoloader can take significant time for each request:

composer dumpautoload -o

The -o flag will convert PSR-0/4 autoloading to classmap to become a faster autoloader.

6. Precompile your assets

If npm is used for your front-end development, you should precompile your assets. This can be done by running the following command:

npm run production

This will compile the assets and create public/assets directory.

This is all for now. Hope you enjoy that.

By Asahi



WWDC22

This year, the Apple Worldwide Developers Conference (WWDC) will be an online-only event, June 6-10. However, Apple said it hosted a face-to-face session at Apple Park on June 6, with some developers and students watching the State of the Union address and video together with the online community.

Credit : Apple

WWDC is traditionally a software-focused event where Apple details its upcoming updates to iOS, iPadOS, macOS, tvOS, and watchOS. Last year, for example, Apple announced a series of software enhancements such as SharePlay support for FaceTime, the ability to store IDs digitally in Apple Wallet, widget support for iPadOS, and new privacy features with its subscription service, iCloudPlus.

But that doesn’t mean WWDC is always about software. Past events have seen the launch of the new Mac Pro and HomePod, as well as the updated iMac and iPad Pro. At Apple’s 2021 conference, it announced that it would be moving its Mac lineup to its own Arm-based Apple Silicon.

You can check out the more detail of the program here if you are interested.

Yuuma



知っておいていただきたいこと – 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を使用したテーブル生成方法とサーバーサイド連携方法をシェアします。
前回の記事でページング処理ができましたので、今回はデータテーブルの各項目にソート処理を追加していきたいと思います。

続きを読む

アプリ関連ニュース

お問い合わせはこちら

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

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

お問い合わせフォーム