📜 ⬆️ ⬇️

Mini API on Lumen

image

The purpose of this publication is to create a simple API for Lumen and to consider its differences from its older brother. All code is available here .

I installed it on homestead box, t.ch. managed by one line:

composer create-project laravel/lumen --prefer-dist Lumen 

Read more about homestead.
')
The project structure is similar to Laravel:

image

The absence of the / config folder is striking. The fact is that Lumen relies entirely on the contents of the .env file. Sample content:

 DB_CONNECTION=mysql DB_USERNAME=homestead DB_PASSWORD=secret DB_DATABASE=lumen 

All possible settings can be found in vendor / laravel / lumen-framework / config /.

So,

DB structure


Suppose we need the essence of the post, plus 2 methods - registration and login.
To create migrations, use the artisan command utility.

 php artisan make:migration create_users_table php artisan make:migration create_posts_table 

Now there are 2 new files in the / database folder. Each has 2 methods, up and down - migration and cancellation of migration.
This is what the up method for the users table looks like:

 //database/*create_users_table.php Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('email')->unique(); $table->string('first_name'); $table->string('last_name'); $table->string('password'); $table->rememberToken(); $table->timestamps(); $table->softDeletes(); }); 

For posts:

 //database/*create_posts_table.php Schema::create('posts', function (Blueprint $table) { $table->increments('id'); $table->string('user_id'); $table->string('content'); $table->timestamps(); $table->softDeletes(); }); 

Migrations are ready, trying to apply them:

 php artisan migrate 

But for some reason the artist does not see the variables from the .env file and complains about the bad connection parameters. In order to export variables, you need to uncomment the line in /bootstrap/app.php:

 Dotenv::load(__DIR__.'/../'); 

Also, by default, ORM Eloquent and facades are disabled. Stuff useful, so I also included them.
Now everything should work out:

image
(art is alias for php artisan)

Also create an eloquent model for these tables. For example, the model of the post:

 use Illuminate\Database\Eloquent\Model; class Post extends Model { /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user() { return $this->belongsTo('Written\Models\User'); } } 

Models allow, with less pain, to give data from methods, since they take care of the relationship of the tables. Of course, the performance of "raw" queries to the database is better, but the speed of development with this approach will steadily degrade. Such queries are relevant, in my opinion, only for statistical samples.

Controllers


In Laravel 5 there is a wonderful Trait, which allows you to do all the registration in two clicks of fingers. Unfortunately, there is no such thing in Lumen. It is also now customary not to write all the routes into one file, but to use annotations, for example:

 /** * @Middleware("auth.token") * @Resource('post') */ class PostsController extends Controller { public function index() {} public function show($id) {} public function store() {} public function update() {} public function destroy() {} } 

This annotation says that the controller is RESTful. So having 1 open file in front of your eyes already has an understanding of how to access methods, and what filters they have. This is done with the help of laravelcollective / annotations . But with Lumen it is incompatible, so all the routes will have to be shoved into /app/http/routes.php:

 $app->get('/', function() use ($app) { return $app->welcome(); }); $app->post('/register', ['uses' => 'App\Http\Controllers\AuthController@postRegister']); $app->post('/login', ['uses' => 'App\Http\Controllers\AuthController@postLogin']); $app->get('/post/{id}', ['uses' => 'App\Http\Controllers\PostsController@show']); $app->get('/post', ['uses' => 'App\Http\Controllers\PostsController@index']); $app->group(['middleware' => 'logged.in'], function($app) { $app->post('/post', ['uses' => 'App\Http\Controllers\PostsController@store']); /** & another protected routes */ }); 

In a normal application, this file becomes monstrous quickly.

Lumen, like Laravel, has Middleware, which can either filter certain requests or do any usefulness for each request. All such filters are in / app / Http / Middleware /. In order for Lumen to know about their existence, you need to add the appropriate classes in /bootstrap.app.php.

Middleware example:

 //app/Http/Middlewared/LoggedInMiddleware.php class LoggedInMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if(!Auth::check()) { return new Response('', 401); } return $next($request); } } 

The described filter produces an http code 401 if the request comes from an unauthorized user.

Controller example:

 //app/Http/Controller/PostsController.php /** * Class PostsController * @package App\Http\Controllers */ class PostsController extends Controller { public function index() { return $this->respondWithData(Post::with('user')->all()->toArray()); } public function show($id) { return $this->respondWithData(Post::find($id)->with('user')->get()->toArray()); } public function store() { $rules = [ 'text' => 'required', ]; $input = $_POST; $validator = Validator::make($input, $rules); if ($validator->fails()) { return $this->respondWithFailedValidation($validator); } $post = new Post; $post->content = $input['content']; $post->user()->associate(Auth::user()); $post->save(); return $this->show($post->id); } // public function delete() {} } 

An example of the profit from using Eloquent can be seen in the show () method. The client is given not only information about the post, but also about the associated user.

The respondWith * methods are helper to give the code some kind of organization. In general, the method can even return a regular string.

Conclusion


No wonder that Lumen is fully compatible with Laravel, because after all that has been written, I do not feel that I have written something about Lumen.

But still, when developing even the above described functional, a sediment remained:
- incompatible with libraries written for Laravel. The same annotations are the de facto standard;
- to enter you need to know Laravel, because The things described in the Laravel docks do not work, and little is written in the Lumen docks. You have to watch the source. For example, facades - not all is available. Missing need to register yourself, pens;
- I failed to get tests, because for some reason, $ _POST does not arrive in the method.

I have only one two questions - why do I need Lumen when I have Laravel? Are there people who want mega-performance and at the same time do not write their decision?

Source: https://habr.com/ru/post/257073/


All Articles