0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【備忘録:2025/10/24】public function __construct、__invoke、DB::xxx();

Posted at

はじめに

自分が理解できていない部分を整理しながら、知識を少しずつ深めていくことを目的にこの記事を書いています。

そのため、内容の中には誤りが含まれている可能性もありますが、その点はご容赦ください。

間違いなどがあれば、ぜひコメントなどで教えていただけると嬉しいです!🙇

今日整理していく内容

  • public function __construct
  • public function __invoke
  • DB::xxx();

public function __construct

はい、これも謎でしたね。function の後は作りたい関数名って決まっているんじゃないですか??って思いますよね。

__construct() は少し使い方が難しいイメージですが、以下のような簡単なコードで紹介します。

class User {
    public string $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }
}

$user = new User('Kota');
echo $user->name; // Kota

ここでは、new User('Kota') のタイミングで __construct() が自動で実行されるみたいです。

public function __invoke

__invoke はなんとなく理解しているつもりです!以前、コードレビューの時に指摘されてからなるべく使うように意識しています。

また、その方のコードはよく見る機会があるので、「あ!ここでも使っている!!」って思いながら、美しいコードだなぁ〜と思ってよく見てます!

__invoke() は、オブジェクトを関数のように呼び出せるようにする特殊メソッドです。

class Hello {
    public function __invoke(string $name)
    {
        echo "Hello, $name!";
    }
}

$greet = new Hello();
$greet('Kota'); // Hello, Kota!

$greet('Kota') のように、関数っぽく使えるようになります。

DB::xxx();

これもなかなか癖がありますよね。最初に use 文でインポートして使います。

use Illuminate\Support\Facades\DB;

Laravel が提供する データベース操作用の「DBファサード」 です。DB::select(), DB::insert(), DB::table() などを使って、SQLを書かずにデータを操作できます。

以下は公式のサンプルコードです👇

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class UserController extends Controller
{
    /**
     * Show a list of all of the application's users.
     */
    public function index(): View
    {
        $users = DB::table('users')->get();

        return view('user.index', ['users' => $users]);
    }
}

DB::table('users')->get(); で、データベースの users テーブルからすべてのデータを取得して、return で変数 $users をビューに渡し、一覧表示しているイメージです。

まとめ

ここまで読んでいただきありがとうございました!

今回の記事では、

  • public function __construct
  • public function __invoke
  • DB::xxx();

について整理しました。少しずつでも理解を深めながら、明日も頑張ります!💪

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?