Search code examples
laravellumen

Illuminate me - get functionality in Lumen of this code


I'm learning lumen, never worked with it or its big brother laravel. I did code "vanilla" PhP for about 1 1/2 years though and I'm familiar with the functionality of PDO requests for example.

So I'm using this tutorial: https://www.youtube.com/watch?v=6Oxfb_HNY0U

After I created my db which so far only has the table "articles" with 6 columns, I tried out the following code from the tutorial:

web.php (residing inside "routes" folder):

<?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 (located inside "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 (located inside "app" folder):

<?php

namespace App;


use Illuminate\Database\Eloquent\Model;

class Article extends Model
{

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


}

ArticleController.php (residing inside \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());
    }
}

Now what confuses is how this syntax works:

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

coming from ArticleController.php.

As far as I understand, the call to this function has been defined inside web.php with this:

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

Here, the table to access was defined and then the function to handle the response from the DB also defined. So far I'm pretty "good to go" I think.

But when I now try to "translate" this framework syntax into its PHP correlate, I get confused. What does:

Article::all()

inside

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

do? What is Article? I guess it is one row from the table articles. The naming would be arbitrary here, would it? And then "all()". The first guess that came to my mind was the PDO equivalent "fetchAll()". Is that true? Is the behavior the same if I used fetchAll() on a PDO based query to the DB? The syntax itself is kind of intuitive, but it still leaves room for different interpretations. Since Article, which I suppose is a single row from the response, is "piped" to the "all()" function, all() could just as well do something different than the "fetchAll()" which is always applied to the FULL RESULT of a query and not just a single resultset (=row).

And furthermore, does anyone know a good tutorial for Lumen? Its really horrible working just with the official docs, because the framework is so modular and just reading through the different sections doesnt help me setting up a small testproject from which I could learn how to actually USE the framework, not just describe it...


Solution

  • Laravel and Lumen both use Eloquent models which is what your Article is, an Eloquent model.

    Models allow you to query for data in your tables, as well as insert new records into the table.

    The Article::all() returns an Eloquent collection.

    Eloquent collections are an extension of Laravel's Collection class with some handy methods for dealing with query results. The Collection class itself, is merely a wrapper for an array of objects, but has a bunch of other interesting methods to help you pluck items out of the array.

    With the return response()->json(Article::all()); what you're saying is return a response from the endpoint with all of the articles. Articles was originally a collection but it gets transformed into an array which then gets transformed to json in the frontend.

    Basically with Eloquent it's really easy to build up queries and insert into the database, with a simple query such as:

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

    You have access to that whole article now and can associate with it etc. Or you could query the whole results set by doing something such as...

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

    As for recommending sites, you should probably look at the Laravel from scratch series from Laracasts, which can be found here. Don't worry about it being 5.7 as then you can watch the Laravel 6.0 from scratch here.

    This is my go to site for anything Laravel, Jeffery Way (the host) explains things that anyone could understand.

    It's to much to explain in one Stack Overflow post but I'm more than happy to discuss further in a discussion.

    I hope this helped and gave you a few links which you can investivagate further.