覆盖Laravel控制器中的特征方法

时间:2016-06-10 06:42:49

标签: php laravel laravel-5 traits

我无法在Controller类中覆盖特征的方法。这是我的特质方法的一个例子:

protected function resetPassword($user, $password)
{
    $user->password = bcrypt($password);

    $user->save();

    Auth::login($user);
}

这是我的控制器:

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;

use Illuminate\Foundation\Auth\ResetsPasswords;


class PasswordController extends Controller
{
    use ResetsPasswords {
        resetPassword as newReset;
    }

    /**
     * Create a new password controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    protected function resetPassword($user, $password)
    {

    }
}

我找到了一个例子,但我不确定我是否正确。

1 个答案:

答案 0 :(得分:2)

正如您自己已经完成的那样,您需要为框架特征的resetPassword方法添加别名,然后实现自己的方法:

namespace App\Http\Controllers\Auth;

use Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;

class PasswordController extends Controller
{
    use ResetsPasswords {
        resetPassword as frameworkResetPassword;
    }

    protected function resetPassword($user, $password)
    {
        // Do your custom password reset logic here
        $user->password = bcrypt($password);
        $user->save();
        Auth::login($user);

        // Then you can pass the work over to framework's implementation
        // if that's needed.
        // $this->frameworkResetPassword($user, $password);
    }
}

顺便说一下,Laravel自己的password reset functionality支持登录用户。