6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Traitの関数にクラス内のローカルな名前をつけて呼び出す

Last updated at Posted at 2018-02-24

クラス側で使いたい関数名とトレイトの関数名が被っている場合に、トレイトの関数名にクラス内のローカルな名前をつける事により、トレイトの関数を上書きせずに、クラスからトレイトの関数を呼び出すことができます。

以下はLaravelでAuthenticatesUsersのlogin関数にtraitLoginという名前をつけてクラス側のlogin関数から呼び出す例です。

LoginController.php
<?php

namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

class LoginController extends Controller
{

    use AuthenticatesUsers {
        login as private traitLogin;
    }

    public function login(Request $request) {
        // 独自の処理
        return $this->traitLogin($request);
    }

Laravelの認証回りはトレイトで大体の実装が提供されていますが、一部いじりたかったのでこんな感じにしました。

6
4
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
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?