首页 > 解决方案 > 照亮我 - 在此代码的 Lumen 中获取功能

问题描述

我正在学习流明,从未使用过它或它的大哥 laravel。不过,我编写“vanilla”PhP 代码大约 1 1/2 年,例如,我熟悉 PDO 请求的功能。

所以我正在使用本教程: https ://www.youtube.com/watch?v=6Oxfb_HNY0U

在我创建了迄今为止只有 6 列的“文章”表的数据库之后,我尝试了教程中的以下代码:

web.php(位于“路由”文件夹内):

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/

$router->get('/', function () use ($router) {
    return $router->app->version();
});


$router->group(['prefix' => 'api'], function($router){
  $router->get('articles', 'ArticleController@showAllArticles');
});


$router->get('foo', function () {
    return 'Hello World';
});

$router->post('foo', function () {
    //
});

app.php(位于“bootstrap”内):

<?php

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

(new Laravel\Lumen\Bootstrap\LoadEnvironmentVariables(
    dirname(__DIR__)
))->bootstrap();

/*
|--------------------------------------------------------------------------
| 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(
    dirname(__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
);

/*
|--------------------------------------------------------------------------
| 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([
//     'auth' => App\Http\Middleware\Authenticate::class,
// ]);

/*
|--------------------------------------------------------------------------
| 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);

/*
|--------------------------------------------------------------------------
| 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->router->group([
    'namespace' => 'App\Http\Controllers',
], function ($router) {
    require __DIR__.'/../routes/web.php';
});

return $app;

Article.php(位于“app”文件夹内):

<?php

namespace App;


use Illuminate\Database\Eloquent\Model;

class Article extends Model
{

    protected $fillable = [
        'title', 'description','status'
    ];


}

ArticleController.php(位于 \Http\Controllers 内)

<?php

namespace App\Http\Controllers;

use App\Article;
use Illuminate\Http\Requests;
class ArticleController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    //

    public function showAllArticles(){
      return response()->json(Article::all());
    }
}

现在令人困惑的是这个语法是如何工作的:

return response()->json(Article::all());

来自 ArticleController.php。

据我了解,对该函数的调用已在 web.php 中定义,如下所示:

$router->group(['prefix' => 'api'], function($router){
  $router->get('articles', 'ArticleController@showAllArticles');
});

在这里,定义了要访问的表,然后还定义了处理来自 DB 的响应的函数。到目前为止,我认为我很“好”。

但是当我现在尝试将这个框架语法“翻译”成它的 PHP 关联时,我感到困惑。有什么作用:

Article::all()

里面

return response()->json(Article::all());

做?什么是文章?我想这是表格文章中的一行。这里的命名是任意的,不是吗?然后是“所有()”。我想到的第一个猜测是等效于 PDO 的“fetchAll()”。真的吗?如果我在基于 PDO 的数据库查询中使用 fetchAll(),行为是否相同?语法本身有点直观,但它仍然为不同的解释留下了空间。由于我认为是响应中的单行的 Article 被“管道”到“all()”函数,所以 all() 也可以做一些不同于“fetchAll()”的事情,后者总是应用于查询的完整结果,而不仅仅是单个结果集 (=row)。

此外,有人知道 Lumen 的好教程吗?仅与官方文档一起工作真的很糟糕,因为框架是如此模块化,只是阅读不同的部分并不能帮助我建立一个小的测试项目,从中我可以学习如何实际使用框架,而不仅仅是描述它......

标签: laravellumen

解决方案


Laravel 和 Lumen 都使用 Eloquent 模型,这就是你ArticleEloquent 模型。

模型允许您查询表中的数据,以及将新记录插入表中。

Article::all()返回一个Eloquent集合。

Eloquent 集合是 Laravel 的 Collection 类的扩展,它提供了一些方便的方法来处理查询结果。Collection 类本身只是一个对象数组的包装器,但还有许多其他有趣的方法可以帮助您从数组中提取项目。

return response()->json(Article::all());您所说的是从端点返回所有文章的响应。Articles 最初是一个集合,但它被转换为一个数组,然后在前端转换为 json。

基本上,使用 Eloquent,构建查询并插入数据库非常容易,只需一个简单的查询,例如:

$article = Article::create(['title' => 'My New Article', 'slug' => 'my-new-article']);

您现在可以访问整篇文章并可以与之关联等。或者您可以通过执行诸如...之类的操作来查询整个结果集

$articles = Article::query()->where('slug', 'my-new-article')->first();

至于推荐网站,你可能应该看看 Laracasts 的 Laravel from scratch 系列,可以在这里找到。不要担心它是 5.7,因为你可以在这里从头开始观看 Laravel 6.0。

这是我访问任何 Laravel 的网站,Jeffery Way(主持人)解释了任何人都可以理解的事情。

在一篇 Stack Overflow 帖子中要解释的内容太多了,但我很乐意在讨论中进一步讨论。

我希望这对您有所帮助,并为您提供了一些您可以进一步研究的链接。


推荐阅读