【问题标题】:Lumen + Dingo + JWT is not instantiable while buildingLumen + Dingo + JWT 在构建时不可实例化
【发布时间】:2016-07-05 08:28:42
【问题描述】:

我正在尝试为 Lumen + Dingo Rest API 打下基本的工作基础,但我无法弄清楚如何将和平融合在一起。

Lumen 工作正常,但是当我尝试添加 Dingo 时,我得到了各种错误。从Dingo documentation我读到:

获得包后,您可以在 config/api.php 文件或服务提供程序或引导文件中配置提供程序。

'jwt' => 'Dingo\Api\Auth\Provider\JWT'

app('Dingo\Api\Auth\Auth')->extend('jwt', function ($app) {
   return new Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']);
});

我已经安装了 Lumen 的新副本,但我没有看到任何 config/api.php,所以我假设我使用这段代码放置在我的 bootstrap/app.php

这就是我的bootstrap/app.php 的样子:

<?php

require_once __DIR__.'/../vendor/autoload.php';

try {
    (new Dotenv\Dotenv(__DIR__.'/../'))->load();
} catch (Dotenv\Exception\InvalidPathException $e) {
    //
}

$app = new Laravel\Lumen\Application(
    realpath(__DIR__.'/../')
);

$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);

$app->singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);

$app->register(Dingo\Api\Provider\LumenServiceProvider::class);

app('Dingo\Api\Auth\Auth')->extend('jwt', function ($app) {
    return new Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']);
});

$app->group(['namespace' => 'App\Api\Controllers'], function ($app) {
    require __DIR__.'/../app/Api/routes.php';
});

return $app;

运行时出现以下错误:

BindingResolutionException in Container.php line 752:

Target [Tymon\JWTAuth\Providers\JWT\JWTInterface] is not instantiable while building [Tymon\JWTAuth\JWTAuth, Tymon\JWTAuth\JWTManager].

in Container.php line 752
at Container->build('Tymon\JWTAuth\Providers\JWT\JWTInterface', array()) in Container.php line 633
at Container->make('Tymon\JWTAuth\Providers\JWT\JWTInterface', array()) in Application.php line 205
at Application->make('Tymon\JWTAuth\Providers\JWT\JWTInterface') in Container.php line 853
at Container->resolveClass(object(ReflectionParameter)) in Container.php line 808
at Container->getDependencies(array(object(ReflectionParameter), object(ReflectionParameter), object(ReflectionParameter)), array()) in Container.php line 779
at Container->build('Tymon\JWTAuth\JWTManager', array()) in Container.php line 633
at Container->make('Tymon\JWTAuth\JWTManager', array()) in Application.php line 205
at Application->make('Tymon\JWTAuth\JWTManager') in Container.php line 853
at Container->resolveClass(object(ReflectionParameter)) in Container.php line 808
at Container->getDependencies(array(object(ReflectionParameter), object(ReflectionParameter), object(ReflectionParameter), object(ReflectionParameter)), array()) in Container.php line 779
at Container->build('Tymon\JWTAuth\JWTAuth', array()) in Container.php line 633
at Container->make('Tymon\JWTAuth\JWTAuth', array()) in Application.php line 205
at Application->make('Tymon\JWTAuth\JWTAuth') in Container.php line 1178
at Container->offsetGet('Tymon\JWTAuth\JWTAuth') in app.php line 95
at {closure}(object(Application))
at call_user_func(object(Closure), object(Application)) in Auth.php line 216
at Auth->extend('jwt', object(Closure)) in app.php line 96
at require('/vagrant/dev_src/api/bootstrap/app.php') in index.php line 14

只有当我删除以下代码时它才能再次工作:

app('Dingo\Api\Auth\Auth')->extend('jwt', function ($app) {
    return new Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']);
});

更新 1

.env文件:

APP_ENV=local
APP_DEBUG=true
APP_KEY=xxxxSECRETxxxx

CACHE_DRIVER=file
QUEUE_DRIVER=sync

JWT_SECRET=yyyySECRETyyyy

API_VENDOR=MyCompanyName
API_STANDARDS_TREE=vnd
API_PREFIX=api
API_VERSION=v1
API_NAME="MyCompanyName API"
API_CONDITIONAL_REQUEST=false
API_STRICT=false
API_DEFAULT_FORMAT=json

【问题讨论】:

    标签: php jwt lumen dingo-api lumen-5.2


    【解决方案1】:

    你必须做很多事情。这是指南:

    您必须手动绑定CacheManager 实现:

    $app->singleton(
        Illuminate\Cache\CacheManager::class,
        function ($app) {
            return $app->make('cache');
        }
    );
    

    还需要绑定AuthManager实现:

    $app->singleton(
        Illuminate\Auth\AuthManager::class,
        function ($app) {
            return $app->make('auth');
        }
    );
    

    在注册Dingo\Api\Provider\LumenServiceProvider之前,您必须先注册Tymon\JWTAuth\Providers\JWTAuthServiceProvider

    $app->register(Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class);
    $app->register(Dingo\Api\Provider\LumenServiceProvider::class);
    

    在注册Tymon\JWTAuth\Providers\JWTAuthServiceProvider之前,你需要创建一个config_path函数,因为Lumen不支持这个全局函数。

    /**
     * Because Lumen has no config_path function, we need to add this function
     * to make JWT Auth works.
     */
    if (!function_exists('config_path')) {
        /**
         * Get the configuration path.
         *
         * @param string $path
         *
         * @return string
         */
        function config_path($path = '')
        {
            return app()->basePath().'/config'.($path ? '/'.$path : $path);
        }
    }
    

    这是我完整的bootstrap/app.php 文件:

    <?php
    
    require_once __DIR__.'/../vendor/autoload.php';
    
    try {
        (new Dotenv\Dotenv(__DIR__.'/../'))->load();
    } catch (Dotenv\Exception\InvalidPathException $e) {
        //
    }
    
    /*
    |--------------------------------------------------------------------------
    | Create The Application
    |--------------------------------------------------------------------------
    |
    | Here we will load the environment and create the application instance
    | that serves as the central piece of this framework. We'll use this
    | application as an "IoC" container and router for this framework.
    |
    */
    
    $app = new Laravel\Lumen\Application(
        realpath(__DIR__.'/../')
    );
    
    $app->withFacades();
    
    $app->withEloquent();
    
    /*
    |--------------------------------------------------------------------------
    | Register Container Bindings
    |--------------------------------------------------------------------------
    |
    | Now we will register a few bindings in the service container. We will
    | register the exception handler and the console kernel. You may add
    | your own bindings here if you like or you can make another file.
    |
    */
    
    $app->singleton(
        Illuminate\Contracts\Debug\ExceptionHandler::class,
        App\Exceptions\Handler::class
    );
    
    $app->singleton(
        Illuminate\Contracts\Console\Kernel::class,
        App\Console\Kernel::class
    );
    
    $app->singleton(
        Illuminate\Contracts\Routing\ResponseFactory::class,
        Illuminate\Routing\ResponseFactory::class
    );
    
    $app->singleton(
        Illuminate\Auth\AuthManager::class,
        function ($app) {
            return $app->make('auth');
        }
    );
    
    $app->singleton(
        Illuminate\Cache\CacheManager::class,
        function ($app) {
            return $app->make('cache');
        }
    );
    
    /*
    |--------------------------------------------------------------------------
    | Register Middleware
    |--------------------------------------------------------------------------
    |
    | Next, we will register the middleware with the application. These can
    | be global middleware that run before and after each request into a
    | route or middleware that'll be assigned to some specific routes.
    |
    */
    
    // $app->middleware([
    //    App\Http\Middleware\ExampleMiddleware::class
    // ]);
    
    // $app->routeMiddleware([
    //     //
    // ]);
    
    /*
    |--------------------------------------------------------------------------
    | Register Service Providers
    |--------------------------------------------------------------------------
    |
    | Here we will register all of the application's service providers which
    | are used to bind services into the container. Service providers are
    | totally optional, so you are not required to uncomment this line.
    |
    */
    
    // $app->register(App\Providers\AppServiceProvider::class);
    // $app->register(App\Providers\AuthServiceProvider::class);
    // $app->register(App\Providers\EventServiceProvider::class);
    
    // JWTAuth Dependencies
    /**
     * Because Lumen has no config_path function, we need to add this function
     * to make JWT Auth works.
     */
    if (!function_exists('config_path')) {
        /**
         * Get the configuration path.
         *
         * @param string $path
         *
         * @return string
         */
        function config_path($path = '')
        {
            return app()->basePath().'/config'.($path ? '/'.$path : $path);
        }
    }
    
    $app->register(Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class);
    $app->register(Dingo\Api\Provider\LumenServiceProvider::class);
    
    $app->make(Dingo\Api\Auth\Auth::class)->extend('jwt', function ($app) {
        return new Dingo\Api\Auth\Provider\JWT(
            $app->make(Tymon\JWTAuth\JWTAuth::class)
        );
    });
    
    /*
    |--------------------------------------------------------------------------
    | Load The Application Routes
    |--------------------------------------------------------------------------
    |
    | Next we will include the routes file so that they can all be added to
    | the application. This will provide all of the URLs the application
    | can respond to, as well as the controllers that may handle them.
    |
    */
    
    $app->group(['namespace' => App\Api\Controllers::class], function ($app) {
        require __DIR__.'/../app/Api/routes.php';
    });
    
    return $app;
    

    更新 1

    我使用 Lumen 和 Dingo API here 制作了一个简单的 POC。

    【讨论】:

    • 你付出了很大的努力,还做了一个 git repo,非常感谢!我将克隆一个 repo 并将其用作我的 API 的基础,非常感谢!
    • 一个问题。在您的仓库中,我看到您有一个 .env.example 文件,以及 /config 中的一些配置文件。要配置 Dingo,我应该使用 .env 文件还是配置文件,或者两者都使用。
    • Lumen 仍在使用.env 文件。我推送配置文件仅用于学习目的以及其他不由.env 文件确定的配置;比如auth.guardsapi.errorFormat
    • 好的,很清楚。我使用了 .env 文件,并设置了正确的变量。编辑了我的主题帖子。直到现在,当我浏览到 http://localhost:8080/api/ 时,我才得到一个 403 页面。文件的所有权限都很好。
    • 我正在使用 Lumen 构建一个 RESTful 应用程序。我面临同样的问题和许多其他事情。所以,我将它们包装在这个article 中。我希望你能发现它很有用。我仍在测试与我在 Lumen 中所做的一些工作的集成。如果我发现更多东西,我会继续更新那个帖子。
    猜你喜欢
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 2016-07-26
    • 2017-07-24
    • 2018-11-28
    • 2018-01-02
    • 2019-03-30
    • 2019-01-27
    相关资源
    最近更新 更多