Skip to content
Permalink
master
Switch branches/tags
Go to file
 
 
Cannot retrieve contributors at this time

Hook

1. 瀹氫箟 Hook

婕旂ず濡備綍閫氳繃 Hook 瀹炵幇 Basic Authorization 鐧诲綍鏍¢獙

/**
 * 绠鍗曠櫥褰曟牎楠
 *
 * 瀹炵幇浜 Basic Authorization
 * @package App\Hooks
 */
class BasicAuth implements HookInterface
{
    /**
     * @param Request $request
     * @param callable $next
     * @return Response
     */
    public function handle(Request $request, callable $next)
    {
        $auth = $request->headers->get('Authorization');
        $auth or \PhpBoot\abort(new UnauthorizedHttpException('Basic realm="PhpBoot Example"', 'Please login...'));
        $auth = explode(' ', $auth);
        $auth[1] == md5("{$this->username}:{$this->password}") or fail(new UnauthorizedHttpException('Basic realm="PhpBoot Example", "Invalid username or password!"'));
        return $next($request);
    }

    /**
     * @var string
     */
    public $username;
    /**
     * @var string
     */
    public $password;
}

鍙互鐪嬪埌锛孒ook 鍙渶瑕佺户鎵縃ookInterface锛屽疄鐜 handle 鏂规硶銆

2. 浣跨敤 Hook

涓洪渶瑕佺殑鎺ュ彛娣诲姞姝 Hook

2.1. 閫氳繃 @hook 娣诲姞 Hook

/**
 * @route POST /books/
 * @param Book $book {@bind request.request}
 * @hook \App\Hooks\BasicAuth 鎸囧畾姝ゆ帴鍙i渶瑕丅asicAuth鏍¢獙
 */
public function createBook(Book $bok)

涓涓帴鍙e彲浠ユ寚瀹氬涓 Hook锛屾墽琛岀殑椤哄簭渚濈収@hook 瀹氫箟鐨勯『搴忋

2.2. 娣诲姞璺敱鏃舵寚瀹 Hook

Application::addRoute()銆丄pplication::loadRoutes*() 鏂规硶娣诲姞璺敱鏃讹紝鍙互鎸囧畾 Hook 锛屽锛

$app->loadRoutesFromPath($path, [BaseAuth::class]);

2.3. 璁剧疆鍏ㄥ眬 Hook

Application::setGlobalHooks 鐢ㄤ簬璁剧疆鍏ㄥ眬 Hook锛 濡傦細

Application::setGlobalHooks([BaseAuth::class])锛

鍏ㄥ眬 Hook 涓嶄緷璧栦簬鏄惁瀛樺湪璺敱锛屽嵆灏辩畻娌℃湁璇锋眰瀵瑰簲鐨勮矾鐢憋紝鍏ㄥ眬 Hook 杩樻槸浼氳鎵ц銆

鍏充簬 Hook 鐨勬洿澶氱粏鑺傦紝 鍙互鍙傝僜PhpBoot\Controller\Hooks\Cors鐨勫疄鐜般