Lumen and Eloquent
Kyle Waters
Lead Software Architect, Venturedata, LLC
Lumen
- RESTful framework
- Laravel
Eloquent
ORM - Object Relational Model
RESTful API
- Based on HTTP
- /resource/id
- GET,POST,PUT,DELETE,PATCH
Creating a Lumen Project
- composer create-project --prefer-dist laravel/lumen DIR
- Lumen installer
Up and running
- php -S localhost:8000 -t public
- Apache(public directory, allow overrides)
Larvel Homestead is an other option
Memcached is used by default
install php-pecl-memcached
Database Setup
- createuser -P
- createdb -O
- .env
Laravel Artisan Console
- Laravel command line tool
- built in database commands
- can create own commands
Laravel Artisan Console
- php artisan make:migration create_table_users --create=users
- php artisan migrate
- php artisan make:seeder usersTableSeeder
- php artisan db:seed
Laravel Migration Script
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email');
$table->string('first_name',128)->nullable();
$table->string('last_name',128)->nullable();
$table->binary('password');
$table->binary('token')->nullable();
$table->timestamps();
});
Eloquent Model
- app/
- fillable
- table
- hasOne,belongsTo,hasMany,belongsToMany
public function position()
{
return $this->belongsTo('App\Position');
}
Seeding
- php artisan make:seeder usersTableSeeder
- include app/User
- Faker
$faker = Faker\Factory::create();
for ($x = 0; $x < 20; $x++)
{
$user = User::create(array(
'email' => $faker->email,
'first_name' => $faker->firstName,
'last_name' => $faker->lastName,
'password' => $faker->word
));
}
app.php
web.php
- Routing
- Function can be in line or in controller
- Middleware can be injected selectively here
$app->get('/users','UserController@index');
$app->get('/user/{id}','UserController@read');
$app->post('/auth','UserController@auth');
Controller
- Controller for each resource
- Seperate function for each action
- Use Model
- Return JSON
public function index(){
$users = User::all();
return $users;
}
public function update(Request $request,$id){
$user = User::findOrFail($id);
$user->update($request->input());
return $user;
}
PHPUnit
- included in vendor
- can test against full app
$this->json('GET', '/users')->seeJson(['email' => ['test@test.com'],]);
$response = (array)json_decode($this->response->content());
$this->assertEquals(26,count($response));
Authentication
- uncomment AuthServiceProvider in bootstrap/app.php
- uncomment Auth Middleware in bootstrap/app.php
- edit app/Providers/AuthServiceProvider
- add 'middleware' => 'auth' to appropriate routes