Laravel api 路由 class 发现错误

Laravel api route class to found error

我目前正在 SitePoint 上的样板中研究 api 基于 jwt 的身份验证。到目前为止,我已经完成了所有工作,但我仍然停留在这一点上。

我的控制器看起来像这样:

namespace App\Api\V1\Controllers;

use Illuminate\Http\Request;
use Dingo\Api\Routing\Helpers;

use Symfony\Component\HttpKernel\Exception\HttpException;
use JWTAuth;
use App\Http\Controllers\Controller;
use App\Order;
// use App\Api\V1\Requests\LoginRequest;
use Tymon\JWTAuth\Exceptions\JWTException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

在正文中我有这个功能:

  public function checkThis()
  {
    $currentUser = JWTAuth::parseToken()->authenticate();
    $orders = App\Order::first();
    echo $orders;
    function() {
    echo "stll here";
    };
  }

在我的 api 路线下,我在中间件中有这个:

$api->get('orderlist', 'App\Api\V1\Controllers\OrderController@checkThis');

当我在邮递员中 运行 时出现以下错误:"message": "Class 'App\Api\V1\Controllers\App\Order' not found",

我已经尝试了所有我能想到的方法,但它仍然在发生。当我将它从控制器中取出并 运行 它直接在它工作的路线中时。我是 Laravel 和 PHP 的新手,所以我有点卡住了。

以下所有内容都表明您要调用 App\Order::first();

在函数 checkThis 中,您可以将 App\Order::first() 替换为

Order::first() //aliasing version

或将App\Order::first()替换为

\App\Order::first(); //fully qualified Name version

来自 php manual

Example #1 importing/aliasing with the use operator
<?php
namespace foo;
use My\Full\Classname as Another;

// this is the same as use My\Full\NSname as NSname   <-- very important 
use My\Full\NSname;

注意

// this is the same as use My\Full\NSname as NSname   <-- very important 
    use My\Full\NSname;

another php manual

and Inside a namespace, when PHP encounters an unqualified Name in a class name, function or constant context, it resolves these with different priorities. Class names always resolve to the current namespace name. Thus to access internal or non-namespaced user classes, one must refer to them with their fully qualified Name

php manual : fully qualified Name

Fully qualified name

This is an identifier with a namespace separator that begins with a namespace separator, such as \Foo\Bar. The namespace \Foo is also a fully qualified name.

所以如果你想调用函数 App\Order::first ,只需 Order::first,因为

use App\Order;     
equal 
use App\Order as Order ;

别名是 Order 而不是 App\Order完全限定名称\App\Order而不是App\Order

另一方面,当您调用 App\Order::first(); 这意味着您正在调用

App\Api\V1\Controllers\App\Order::first();

所以找不到 class;

这是我的演示

file1.php

<?php
namespace App;
class  Order{
public static function   first(){
echo "i am first";
  }
}

file2.php

<?php
namespace App\Api\V1\Controllers;
include 'file1.php';

use App\Order ;
\App\Order::first();
// and you can do it by 
//  Order::first();  they are equal in this place 

当我运行命令phpfile2.php 它回显 我是第一个